JAVA synchronized

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 21:49   613   0
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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP