线程同步的小问题,是不是永远无法预知?
public class TT 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(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
是不是永远无法预知先执行主线程还是t线程? 当主线程执行调用m2时候m2睡眠不是把cpu让给了t线程了么?让来让去的也不清楚到底怎么让了,希望牛人解释先。