synchronized 没有嵌套 不会死锁
package Java死锁范例;
public class ThreadDeadlock2 {
//这种 没有嵌套 不会死锁
public static void main(String[] args) throws InterruptedException {
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();
Thread t1 = new Thread(new SyncThread2(obj1, obj2), "t1");
Thread t2 = new Thread(new SyncThread2(obj2, obj3), "t2");
Thread t3 = new Thread(new SyncThread2(obj3, obj1), "t3");
t1.start();
Thread.sleep(5000);
t2.start();
Thread.sleep(5000);
t3.start();
}
}
class SyncThread2 implements Runnable{
private Object obj1;
private Object obj2;
public SyncThread2(Object o1, Object o2){
this.obj1=o1;
this.obj2=o2;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " 准备锁"+obj1);
//这种 没有嵌套 不会死锁
synchronized (obj1) {
System.out.println(name + " 锁定 "+obj1);
work();
System.out.println("---------------------------------------------------------");
}
System.out.println(name + " 释放 锁"+obj1);
System.out.println("---------------------------------------------------------");
System.out.println(name + "准备锁"+obj2);
synchronized (obj2) {
System.out.println(name + " 锁定 "+obj2);
work();
}
System.out.println(name + " 释放锁"+ obj2 );
System.out.println(name + "---------------------> finished execution.");
}
private void work() {
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
结果:
t1 准备锁java.lang.Object@3e9041fa
t1 锁定 java.lang.Object@3e9041fa
t2 准备锁java.lang.Object@a8f72d1
t2 锁定 java.lang.Object@a8f72d1
t3 准备锁java.lang.Object@76f1ebbf
t3 锁定 java.lang.Object@76f1ebbf
---------------------------------------------------------
t1 释放 锁java.lang.Object@3e9041fa
---------------------------------------------------------
t1准备锁java.lang.Object@a8f72d1
---------------------------------------------------------
t1 锁定 java.lang.Object@a8f72d1
t2 释放 锁java.lang.Object@a8f72d1
---------------------------------------------------------
t2准备锁java.lang.Object@76f1ebbf
---------------------------------------------------------
t3 释放 锁java.lang.Object@76f1ebbf
---------------------------------------------------------
t2 锁定 java.lang.Object@76f1ebbf
t3准备锁java.lang.Object@3e9041fa
t3 锁定 java.lang.Object@3e9041fa
网友评论