用例子理解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(?)所传入的对象实例相同的话,两个片段使用的是同一个锁。如果传入的实例不同,则使用的不是同一个锁。

原创粉丝点击