2.1.6锁重入(支持继承锁)
来源:互联网 发布:知轩藏书网 编辑:程序博客网 时间:2024/06/08 04:41
某个线程获得了锁,这个锁没有释放之前,再次想要获取对象锁的时候,还是可以获取的。即,一个synchronized方法内部调用另外一个带synchronized的方法,是同一个对象锁。
package cha02.execise07;/** * Created by sunyifeng on 17/9/24. */public class Service { synchronized public void service1() { System.out.println("service1"); service2(); } synchronized public void service2() { System.out.println("service2"); service3(); } synchronized public void service3() { System.out.println("service3");// }}
package cha02.execise07;/** * Created by sunyifeng on 17/9/24. */public class MyThread extends Thread { @Override public void run(){ Service service = new Service(); service.service1(); }}
package cha02.execise07;/** * Created by sunyifeng on 17/9/24. */public class Run { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); }}
运行结果:service1
service2
service3
重入锁支持在父子继承的环境中。
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class Father { public int i = 10; synchronized public void operateFatherMethod() { try { i--; System.out.println("father print i=" + i); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } }}
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class Child extends Father { synchronized public void operateChildMethod() { try { while (i > 0) { // i是从父类继承的 i--; System.out.println("child print i=" + i); Thread.sleep(100); this.operateFatherMethod(); } } catch (InterruptedException e) { e.printStackTrace(); } }}
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class MyThread extends Thread { @Override public void run(){ Child child = new Child(); child.operateChildMethod(); }}
package cha02.execise08;/** * Created by sunyifeng on 17/9/24. */public class Run { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); }}
运行结果:child print i=9
father print i=8
child print i=7
father print i=6
child print i=5
father print i=4
child print i=3
father print i=2
child print i=1
father print i=0
程序分析:
父类方法、子类方法都加了同步锁,子类方法调用父类的方法,子类和父类都操作变量i(自减--)。
阅读全文
0 0
- 2.1.6锁重入(支持继承锁)
- python支持多重继承
- JPA支持继承关系
- Mybatis resultMap支持继承
- POJO属性对拷(支持嵌套和继承)
- SimpleAsyncTaskExecutor(源码)简单的异步任务支持限流,ListenableFutureTask支持注册事件->FutureTask的继承
- Java Interface 支持多继承
- java支持多继承吗?
- 继承RichTextBox,完成代码编辑器,支持语法高亮、行号显示(二);
- C++对象模型---多态性的支持(单一继承下的多态)
- 继承和方法重写如何支持多态性
- Spring事务支持:利用继承简化配置
- springboot使用Freemarker支持模版继承
- 继承(单继承、多继承、菱形继承、虚继承)
- python学习(6)继承
- Java练习--继承(6)
- 设计模式知识连载(6)---继承_2:创建即继承-构造函数继承
- 继承(单继承和多层继承)
- win7如何搭建Python开发环境
- zookeeper-3.4.9安装时,启动正常,但是zkServer.sh status查看出
- Qt的读文件,json解析的操作和主界面的跳转(四)
- 布局优化
- [字典树] Codeforces 557E Ann and Half-Palindrome
- 2.1.6锁重入(支持继承锁)
- Java 获取接口所有实现类
- MFC函数汇总
- 显示时间
- 双六问题(扩展欧几里得模板)
- 实验二——静态链表
- vs(visual studio)2013无法启动IIS Expres Web服务器,解决办法
- 运行selenium时报错:Unsupported major.minor version 52.0
- Java泛型基础知识第二部分整理