public class TT implements Runnable {
int b = 100;

public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(2500);
System.out.println("M1 b = " + b);
}

public synchronized void m2() throws Exception {
Thread.sleep(5000);
b = 2000;
System.out.println("M2 b = " + b);
}

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();
Thread.sleep(10000);
System.out.println(tt.b);
}
}
输出结果:
M2 b = 2000
M1 b = 1000
1000
为什么会先输出M2 b=2000,不是先执行了t.start()方法吗?

解决方案 »

  1.   

    t.start();
    表示新起了一个线程,但是并不表示cpu要立即执行这个线程,有可能main函数的线程cpu时间片还没有完。这样就会执行tt.m2();就把tt锁住了。
    t.start();后面加上
    Thread.sleep(100);
    可以确保t.start();后让main交出cpu时间片,这样就能轮到第二个线程运行m1()方法。
      

  2.   

    你把t.start()改成t.run(),结果会如你所愿,先执行t线程,在执行主函数线程,这是因为线程有4种状态:就绪状态(例如t.start()),运行状态(例如t.run()),阻塞状态(例如t.wait()),终止状态()。就绪状态表示当前处于等待状态,不会马上运行。
      

  3.   

    改成run了就不是启动线程了。和调普通方法就没区别了。