synchronized使用
来源:互联网 发布:免费通话软件 编辑:程序博客网 时间:2024/05/19 16:34
private byte[] b = new byte[0];
public synchronized void getName(){
try {
System.out.println("23123213");
Thread.sleep(1000*20);--为了测试效果明显
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized static void getAge(){
try {
System.out.println("1222");
Thread.sleep(1000*10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void test1(){
synchronized (this) {
System.out.println("23123");
try {
Thread.sleep(1000*10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class StudentSynch implements Runnable {
private Student student;
public StudentSynch(Student student){
this.student = student;
}
@Override
public void run() {
student.test1();
}
}
public class TestSynch {
public static void main(String[] args) {
Student student = new Student();
StudentSynch synch = new StudentSynch(student);
Thread thread = new Thread(synch);
Student student1 = new Student();
StudentSynch synch1 = new StudentSynch(student);
Thread thread1 = new Thread(synch1);
thread.start();
thread1.start();
}
}
说明
1:当synchronized关键字修辞非静态方法时,同一个对象对象调用互斥,一个类的多个对象调用不同步
2:当synchronized关键字修辞静态方法时,一个类的多个对象调用互斥保持同步
3:当synchronized关键字放在代码快中如synchronized (this) {....},调用这个方法的对象互斥,这里的this,代表调用这个方法的对象
4:当synchronized关键字放在代码快中如synchronized (Student.class) {....},一个类的多个对象调用互斥保持同步,只是把同步区域缩短在synchronized区域的方法中而不是整个方法
- synchronized 使用
- synchronized使用
- synchronized使用
- synchronized使用
- Synchronized使用心得
- Synchronized使用心得
- 关于 synchronized 的使用
- synchronized的使用
- synchronized关键字的使用
- 使用synchronized同步
- synchronized的使用
- synchronized 语句的使用
- synchronized关键字的使用 .
- synchronized关键字使用剖析
- synchronized的使用总结
- synchronized 关键字的使用
- synchronized 关键字的使用
- 使用@synchronized指令
- 深度学习笔记整理
- 动态规划--数塔
- Apple Tree DFS+树状数组
- Maven仓库
- 接口----实现
- synchronized使用
- 四大组件共同特点-跨进程数据共享
- 堆排序
- linux集群之----------设置磁盘缓冲参数
- spring boot vue Thymeleaf
- 火丁笔记
- [codeforces864F]Cities Excursions
- ctf学习中有用的网址
- Xctf之调皮的py-py-py