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);
}
}请问这个程序的执行过程是怎样的;tt.m2()不是得在m1()执行完之后才执行的吗?
怎么打印结果是:
1000
b=1000

解决方案 »

  1.   

    注意是时间问题,你加一句就会看到结果了,现在这样子,tt.m2()都马上执行了.
    TT tt = new TT();
    Thread t = new Thread(tt);
    t.start();
    Thread.sleep(1000);
    tt.m2();
    System.out.println(tt.b);
      

  2.   

    可能是在执行到t.start()时
    main方法的时间片还没有用完吧。
    所以就先执行了
    tt.m2();
    System.out.println(tt.b);
      

  3.   

    不要可能,要想线程A和B有预想的执行顺序,例如A要在B执行某项操作后再执行。
    则可以让A等待某个条件变为真,然后再执行关键动作。B则可以在执行完某项操作之后
    将A等待的那个条件设置为真,然后唤醒A.这样在执行关键操作的时候就可以保证严格的
    顺序了。
      

  4.   

    你只是告诉JVM  现在可以运行一个线程了
    至于JVM是不是在这个时间点上启动线程,就不是你的事了需要明显等待线程处理的函数,不应该用Runnable接口,而是Callable接口
      

  5.   

    线程的启动需要一定的时间Thread t = new Thread(tt);
    t.start();而main线程早就启动了的
      

  6.   

    Thread t = new Thread(tt);
    t.start();
    只是启动了线程,
    在main线程中,
    main线程还没有运行完呢,
    所以线程t没有运行
    所以tt.m2()它是在主线程中的,它会先运行.
    这和你的线程调度有一定的关系.