JAVA synchronized

来源:互联网 发布:java ee下载安装 编辑:程序博客网 时间:2024/06/05 01:12
JAVA 关于synchronized的一些辅助理解程序:
public class Test1 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;/*System.out.println(b);*/}public void run(){try{m1();}catch(Exception e){e.printStackTrace();}}public static void main(String[] args) throws Exception{Test1 tt =new Test1();Thread t = new Thread(tt);t.start();tt.m2();System.out.println(tt.b);}}
打印结果:2000         b = 2000
此时给m2方法也加上锁:那么程序首先执行run()方法,然后是m1()方法,m1休眠时期(5s),执行m2()方法,因为m2和m1都加了锁,所以在m1解锁前,m2是访问不了b的,因此m2()休眠结束,就是执行输出b的值,仍然是1000,最后执行m1()输出b=1000
public class Test1 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{  Test1 tt =new Test1();  Thread t = new Thread(tt);  t.start();  tt.m2();  System.out.println(tt.b);
 }}
打印结果 :1000          b = 1000

原创粉丝点击