public class SynchronizedExcercises {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnabe myRunnabe = new MyRunnabe();
Thread thread1 = new Thread(myRunnabe);
thread1.start();
myRunnabe.method2();
}
}
public class MyRunnabe implements Runnable {
private int b = 0;
@Override
public void run() {
// TODO Auto-generated method stub
method1();
}
public synchronized void method1() {
this.b = 100;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("b = " + this.b + this.toString());
}
public void method2() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.b = 500;
System.out.println("b = " + this.b);
}
}
这个计算结果为什么得出的结果是:
500
500
我的思路:method1()方法属于synchronized方法,会锁定MyRunnabe的监视器,这个时候虽然其中调用了sleep(5000),但是此时执行method2()方法法时会因为this.b被锁定而阻塞,应该是等method1()执行完了再执行this.b = 500这条语句,其计算结果应该为:
100
500
求解!