线程 synchronized

来源:互联网 发布:刷机恢复数据 编辑:程序博客网 时间:2024/04/30 00:39
 


public class TestSy implements Runnable{

 int b=100;
 
 public synchronized void method1()throws Exception{
  b=500;
  Thread.sleep(5000);
  System.out.println("b === "+b);
 }
 public void method2(){
  System.out.println(b);
 }
 public void run(){
  try{
   method1();
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args)throws Exception {
  // TODO Auto-generated method stub
  TestSy tt=new TestSy();
  Thread t1=new Thread(tt);
  t1.start();
  
  
  Thread.sleep(1000);
  tt.method2();
 }

}

 

结果为:

500
b === 500

出现这种结果前提是新建的线程必须启动起来,否则会出现 100    b===500的结果。

根据睡眠时间判断谁先执行,谁后执行。

synchronized只是锁定了该方法,