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();
   }
}
以上代码运行结果:
     D:\java>javac TT.java
     D:\java>java TT
      b = 1000我的理解是:当线程t执行到m1()时先把b的值改为1000,然后进程sleep状态,接着主线程调用m2(),m2()休眠2500率先醒过来,而后把b的值改成2000了,所以我不懂结果为什么是1000,小弟初学,对同步问题不是很懂,请大家帮帮忙,解析一下,在此先说声谢谢了...

解决方案 »

  1.   

    因为线程的调度需要时间所以先执行的是tt.m2(); 这个main线程又因为synchronized方法同步了 m2 m1 这2个方法(意思是说不论他们是不是在一个线程里面 一个时刻只能执行一个方法)所以m1需要等m2执行好了再可以执行这样你就明白了public class TT implements Runnable {
    int b = 100; public synchronized void m1() throws Exception {
    System.out.println("m1 started!!");
    b = 1000;
    Thread.sleep(5000);
    System.out.println("m1's b = " + b);
    } public synchronized void m2() throws Exception {
    Thread.sleep(2500);
    b = 2000;
    System.out.println("m2's 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();
    }
    }
      

  2.   

    你再这样试一试  就会有新的体会了t.start();
    Thread.sleep(1);
    tt.m2();
      

  3.   

    线程的调度需要时间 所以先执行的是tt.m2(); 这个main线程 又因为synchronized方法同步了 m2 m1 这2个方法(意思是说不论他们是不是在一个线程里面 一个时刻只能执行一个方法) 所以m1需要等m2执行好了再可以执行 
      

  4.   

    http://blog.csdn.net/huangshaojun/archive/2008/04/17/2299101.aspx
    看看这个
      

  5.   

    多线线程的调度是不可控的,它有可能如楼主所说的先执行t线程,也可能先执行main线程。所以出现这种情是完全可能的,建议楼主可以多运行几次,就会有不同的结果了。
      

  6.   

    你没有对主线程和t线程做同步,所以他们之间谁先运行是不可控的
    改成下面这样应该就可以了:public class Demo implements Runnable{
      private int b = 100;
    //  private static Boolean flag = true; 
      public synchronized void m1() throws Exception{
          b = 1000;
    //    Thread.sleep(5000);
          this.wait();
          System.out.println("b = "+b);
      }
     
      public synchronized void m2() throws Exception{
    //      Thread.sleep(2500);
          b = 2000;
          this.notifyAll();
      }
     
      public void run(){
          try{
              m1();
          }catch(Exception e){
              e.printStackTrace();
          }
      }
      public static void main(String[] args) throws Exception{
          Demo tt = new Demo();
          Thread t = new Thread(tt);
          t.start();
          Thread.sleep(1000);
          tt.m2();
      }
    }