用例子理解synchronized
来源:互联网 发布:目标软件倒闭 编辑:程序博客网 时间:2024/06/01 10:23
public class Test3 {public static void main(String[] args){new Thread(){public void run(){new one().start();}}.start();new Thread(){public void run(){new two().startTwo();}}.start();}}class two {void startTwo(){Single single= Single.getInstance();synchronized(this){System.out.println("two1");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("two2");single.sleep("two");}}}class one {void start(){Single single= Single.getInstance();synchronized(this){System.out.println("one1");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("one2");single.sleep("one");}}}class Single {private static Single instance = new Single();private Single(){}static Single getInstance(){return instance;}void sleep(String number){try {System.out.println("start "+number);Thread.sleep(3000);System.out.println("end "+number);} catch (InterruptedException e) {e.printStackTrace();}}}
打印结果:
two1
one1
one2
two2
start one
start two
end two
end one
public class Test3 {public static void main(String[] args){new Thread(){public void run(){new one().start();}}.start();new Thread(){public void run(){new two().startTwo();}}.start();}}class two {void startTwo(){Single single= Single.getInstance();synchronized(single){System.out.println("two1");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("two2");single.sleep("two");}}}class one {void start(){Single single= Single.getInstance();synchronized(single){System.out.println("one1");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("one2");single.sleep("one");}}}class Single {private static Single instance = new Single();private Single(){}static Single getInstance(){return instance;}void sleep(String number){try {System.out.println("start "+number);Thread.sleep(3000);System.out.println("end "+number);} catch (InterruptedException e) {e.printStackTrace();}}}
最后打印的结果:
one1
one2
start one
end one
two1
two2
start two
end two
在不同类中,synchronized(?)所传入的对象实例相同的话,两个片段使用的是同一个锁。如果传入的实例不同,则使用的不是同一个锁。
- 用例子理解synchronized
- 用synchronized实现简单例子
- synchronized理解
- synchronized 理解
- synchronized 理解
- synchronized 理解
- synchronized理解
- Synchronized理解
- 理解synchronized
- 用例子理解排列组合
- Thread的Synchronized例子
- synchronized 自己的例子
- 线程synchronized 例子
- Java synchronized 例子
- 关于java的synchronized关键字,wait(),notify() 的例子,方便大家快速理解和应用。
- 理解synchronized(Object)锁
- 深入理解synchronized
- java thread synchronized 理解
- css样式表
- Delphi图像处理
- 抽象类和接口不能直接实例化
- nosql mongodb 学习-----第二天 高级操作之查询命令
- Hibernate N+1问题
- 用例子理解synchronized
- hdu 1867 kmp裸题
- windows编程常见错误(1)playsound的错误
- LeetCode——Divide Two Integers
- 1381. a*b
- android 数据库 sqlite数据类型(时间 日期 double等)
- [JavaScript] 兼容IE、FireFox、Chrome等浏览器的xml处理函数(xml同步/异步加载、xsl转换、selectSingleNode、selectNodes)
- 论#pragma comment和winmm.lib函数(为什么palysound出现错误原因)
- 水仙花