public class TestTT implements Runnable{
int b = 100;

public synchronized void m1()throws Exception{
b =1000;

Thread.sleep(5000);

System.out.println("b=" + b);
}

public void m2()throws Exception{
Thread.sleep(2500);
b = 2000;

}

public void run(){

try{
m1();
}catch(Exception e){}

}

public static void main(String args[])throws Exception{
TestTT tt = new TestTT();

Thread t = new Thread(tt);

t.start();


tt.m2();

System.out.println(b);
}
}
===============================
这里面结果是2000,b=2000,当m2被synchronized修饰以后结果就变成1000,b=1000,我怎么都分析不大明白这个程序得执行过程,谁能帮我解释清楚?

解决方案 »

  1.   

    第一, b没有设为static, 不知道System.out.println(b);怎么编译通过的..
    第二, 把b改为static,或者用tt.b, 我这里的运行结果是2000, b=1000
    这个结果说得通,两个对象调用了两个不同的synchronized方法,没有锁定的情况出现
    你参考一下
      

  2.   

    你的程序System.out.println(b);能通过吗?synchronized只能锁定不让别的线成在执行这个方法,Thread.sleep(5000);后,cpu就会执行其他方法m2()就会执行.不知道这么说你懂不懂,你可以在
    public synchronized void m1()throws Exception{
    b =1000;
    System.out.print("b前="+b);
    Thread.sleep(5000);System.out.println("b=" + b);
    }
    看看执行效果
      

  3.   

    不好意思,最后一行是System.out.println(tt.b);
      

  4.   

    首先,当m1和m2方法都设为synchronized了之后 把该类this变量作为同步锁的线程无法同时访问这两个方法,也就是说同时有且只有一个线程能访问其中任一个方法。这里有两个线程 thread-t 和thread-main1)thread-main 先进入了m2方法 b被赋为2000 随后 thread-main离开了m2方法
    2)一等thread-main离开了m2方法,即释放了同步锁this,thread-t就能拿到同步锁,同时进入了m1方法,b随即被赋为1000,然后沉睡5秒,该线程进入sleep状态
    3)这时thread-main正好进入执行打印语句段,打印出了b,b值为1000
    4)thread-t睡眠结束,进入打印语句,打印出了b,b值为1000over!
      

  5.   

    不好意思,我对synchronized理解错误. 看了楼上说的恍然大悟.
    在我机器上tt.m2()释放锁后,System.out.println(tt.b)在m1()前执行,所以打印出来总是2000,b=1000.
    我在tt.m2()后加上Thread.sleep(1000),结果就是1000,b=1000了
    sorry~