synchronized使用

来源:互联网 发布:免费通话软件 编辑:程序博客网 时间:2024/05/19 16:34
public class Student {
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区域的方法中而不是整个方法


原创粉丝点击