public class TT implements Runnable {
int b = 100;

public synchronized void m1() throws Exception{
//Thread.sleep(2000);
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);
}
}
的运行结果是什么啊?是怎么运行的啊

解决方案 »

  1.   

    结果是
    1000
    b = 1000执行顺序看注释:
    public class TT implements Runnable{
      int b = 100;  public synchronized void m1() throws Exception{
        //Thread.sleep(2000);
        
        b = 1000;  // 4
        Thread.sleep(5000);  // 5
        System.out.println("b = " + b);  // 7
      }  public synchronized void m2() throws Exception{
        Thread.sleep(2500); // 2
        b = 2000; // 3
      }  public void run(){
        try {
          m1();
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }  static TT tt = new TT();
      public static void main(String[] args) throws Exception{
        Thread t = new Thread(tt);
        t.start();    tt.m2(); // 1
        System.out.println(tt.b);  // 6
      }
    }从2到4因为同步关系,线程会等待,跑完3之后才能4.
      

  2.   

    synchronized  相当于一个锁子,别人不能影响到锁住的东西
    比如 m2() 是synchronized
    Thread.sleep(2500); 睡 2500毫秒
    这个时候其他线程打断不了这个线程
    也就是说无论睡多久其他线程都要等这个线程结束后才能开始
    如果不是synchronized的 可能在睡的同时 其他线程可以运行
      

  3.   

    因为你使用的是Thread.sleep(),两个方法都将主线程阻塞了,如果想阻塞当前线程Thread.currentThread().sleep(), 因此基本上运行完这个程序需要7500ms
    但是结果是不唯一的,在我的机器上cpu空闲时为:
    2000
    b=1000
    忙时还出现过:
    1000
    b=1000
      

  4.   

    为什么tt.m2()先运行,而不是t.start()启动的线程啊。而且为什么m1()方法的线程,比m2()线程运行的晚啊。麻烦高手多多指教……