public class SynchronizendTest1 implements Runnable { int b = 10;

public synchronized void m1() throws Exception {
b=1000;
Thread.sleep(3000);
System.out.println("b="+b);
}

public void m2(){
System.out.println(b);
}

public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String args[]) throws Exception{
SynchronizendTest1 st1=new SynchronizendTest1();
Thread t=new Thread(st1);
t.start();
Thread.sleep(1000);
st1.m2();
}

}结果:1000 
b=1000。
问题就出现在我把主方法里的Thread.sleep(1000)取消,则结果:10 b=1000.
m1()方法已经是同步方法了。执行到Thread.sleep(3000); b都等于1000了。是这样吗?和主方法里的Thread.sleep(1000)有什么关系 ???

解决方案 »

  1.   

    这程序……实在是…… 要说的话,主线程那个 sleep 1秒,实际上起了一个不严谨的 CountDownLatch 的作用……import java.util.concurrent.CountDownLatch;
    public class SynchronizedTest1 implements Runnable {  volatile int b = 10;
      CountDownLatch cd = new CountDownLatch(1);
      public void m1() throws Exception {
        
        b = 1000;
        
        cd.countDown();
        
        Thread.sleep(3000);
        System.out.println("b=" + b);
      }  public void m2() {
        
        System.out.println(b);
      }  @Override
      public void run() {
        
        try {
          
          m1();
        }
        catch(Exception e) {
          
          e.printStackTrace();
        }
      }  public static void main(String args[]) throws Exception {
        
        SynchronizedTest1 st1 = new SynchronizedTest1();
        Thread t = new Thread(st1);
        t.start();
        
        st1.cd.await();
        
        st1.m2();
      }
    }
      

  2.   

    顺便说一句,那个public synchronized void m1()里的 synchronized 除了增加运行成本外没起任何作用,因为你的 m2() 没加同步。
      

  3.   

    m2()没加同步,m1()的synchronized不起啥作用。
      

  4.   

    synchronized 关键字只是对于“这个对象的此方法”加上锁,对于其他的方法是不加锁的。
      

  5.   

    你这程序加不加synchronized没有任何区别啊