黑马程序员技术交流社区
标题:
什么时候产生死锁,该怎么办?
[打印本页]
作者:
sishuidliunian
时间:
2016-5-30 17:27
标题:
什么时候产生死锁,该怎么办?
以前有人发过解答,但有些复杂看不懂。程序如下
package com.itheima;
public class Demo10 {
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 SyncThread(obj1, obj2), "t1");
Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");
t1.start();
Thread.sleep(5000);
t2.start();
Thread.sleep(5000);
t3.start();
}
}
class SyncThread implements Runnable {
private Object obj1;
private Object obj2;
public SyncThread(Object o1, Object o2) {
this.obj1 = o1;
this.obj2 = o2;
}
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " 1111 " + obj1);
synchronized (obj1) {
System.out.println(name + " 2222 " + obj1);
work();
System.out.println(name + " 3333 " + obj2);
synchronized (obj2) {
System.out.println(name + " 4444 " + obj2);
work();
}
System.out.println(name + " released lock on " + obj2);
}
System.out.println(name + " released lock on " + obj1);
System.out.println(name + " finished execution.");
}
private void work() {
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
复制代码
t1 1111 java.lang.Object@7943f708
t1 2222 java.lang.Object@7943f708
t2 1111 java.lang.Object@51733472
t2 2222 java.lang.Object@51733472
t3 1111 java.lang.Object@c01b05e
t3 2222 java.lang.Object@c01b05e
t1 3333 java.lang.Object@51733472
t2 3333 java.lang.Object@c01b05e
复制代码
谁能帮我分析下过程
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2