synchronized使用

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区域的方法中而不是整个方法


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值