package thread;public class TT2 implements Runnable{int b = 100;public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception{
Thread.sleep(7000);
b = 2000;
}
public void run() {
try {
m1();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception{
TT2 tt = new TT2();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}}打印的結果是: 1000 b=1000
我不明白這個結果是怎么來的,為什么不是先執(zhí)行m1的鎖呢
3 回答

FFIVE
TA貢獻1797條經(jīng)驗 獲得超6個贊
代碼執(zhí)行順序是 m2 -》打印tt.b -》m1 -》打印b=?,其中打印tt.b時同時在很短時間給b賦值2000和1000,所有第一次打印可能會是1000或2000第二次肯定是b=1000
添加回答
舉報
0/150
提交
取消