public class TT implements Runnable{
int b = 100;
public synchronized void m1()throws Exception
{
b = 1000;
Thread.sleep(3000);
System.out.println("b = " + b);
}
public synchronized void m2() throws InterruptedException 
{
b = 2000;
Thread.sleep(1500);
}
public void run()
{
try
{
m1();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException
{
TT t = new TT();
Thread tt = new Thread(t);
tt.start();
Thread.sleep(2000);
t.m2();
System.out.println(t.b);
}
}
为什么第一个输出的b是等于1000而不是2000呢?
在System.out.println("b = " + b)这句话执行的时候,m2()方法不是已经把b改成2000了吗?
谁能给我详细的解释下吗?谢~~~

解决方案 »

  1.   

    因为同步了啊 public synchronized void m1(){};显然没有好好上课啊  LZsynchronized 的意思是 这个方法里面的代码需要顺序实行不能被其他线程打断所以 t.m2();这个主线程里面的方法不能影响到b的取值  也就是说 当tt sleep(3000);的时候 
    t.m2();只能在等待  因为synchronized锁的关系 然后当tt执行到System.out.println("b = " + b); 
    最后才是  t.m2();
      

  2.   

    您的代码中,两个方法m1() 和 m2() 都加了关键字 synchronized ,这样会程序的执行路径是: 等到m1()执行完毕之后 m2() 才开始执行 。稍微修改下代码
    public synchronized void m1()throws Exception 

      System.out.println("m1开始执行"); 
      b = 1000;  
      Thread.sleep(3000); 
      System.out.println("b = " + b); 

    public synchronized void m2() throws InterruptedException 

      System.out.println("m2开始执行");
      b = 2000;   
      Thread.sleep(1500); 

    运行结果是:
    m1开始执行
    b = 1000
    m2开始执行
    2000

    “b = 1000”输出以后,才输出的“m2开始执行”,这样就知道是 m1 执行完了才执行 m2的 
      

  3.   

    那如果我把m1()里面的睡眠时间改成sleep(5000),再把m2()方法上面的锁去掉,结果为什么是输出:
    b=2000了呢?
      

  4.   

    跟sleep多久没有关系 跟锁有关
    public synchronized void m1(){}; == public void m1() {synchronized(this) {}}
      

  5.   

    那意思是不是这样的:
       一个对象中经过synchronized 限制的多个方法中,同时进行的线程只有一个呢?
      

  6.   


    public static void main(String[] args) throws InterruptedException
    {
    TT t = new TT();
    Thread tt = new Thread(t);
    tt.start();
    Thread.sleep(2000);
    t.m2();
    System.out.println(t.b);
    }
    [/Quote]从这里开始分析,main线程开始执行,到tt.star()时tt这个线程就开始执行你重写的run()方法,run()方法中调用m1(),m1()声明为synchronized,tt这个线程就获得TT 这个对象的锁,但是在没有执行完之前(虽然有睡眠)但是不会放弃这个对象的锁,其他的线程就不能访问该对象其他的synchronized方法,只有等tt这个线程结束以后才能访问,但是其他的线程可以访问这个对象中非synchronized的方法,(也就是你把m2()的synchronized去掉以后的解释)。以下的代码是在你代码的基础上的一点改变,你看哈行不?
    public class Test implements Runnable{ 
    int b = 100; 
    public synchronized void m1()throws Exception 

    b = 1000; 
    Thread.sleep(1000); 
    System.out.println("b = " + b); 

    public  void m2() throws InterruptedException 

    b = 2000; 
    //Thread.sleep(1500); 

    public void run() 

    try 

    m1(); 

    catch(Exception e) 

    e.printStackTrace(); 


    public static void main(String[] args) throws InterruptedException 

    Test t = new Test(); 
    Thread tt = new Thread(t); 
    tt.start(); 
    t.m2(); 
    Thread.sleep(1000); 

    System.out.println(t.b);