public class Threaddemo {
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(500);
t2.start();
Thread.sleep(500);
t3.start();
}
}
class SyncThread implements Runnable{
private Object obj1;
private Object obj2;
public SyncThread(Object o1, Object o2){
this.obj1=o1;
this.obj2=o2;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " acquiring lock on "+obj1);
synchronized (obj1) {
System.out.println(name + " acquired lock on "+obj1);
work();
System.out.println(name + " acquiring lock on "+obj2);
synchronized (obj2) {
System.out.println(name + " acquired lock on "+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();
}
}
}
答案 0 :(得分:2)
你遇到了死锁问题。
t1获取obj1的锁定。然后做一些工作。在平均时间t2,获取obj2的锁并做一些工作。 t3和obj3也一样。
现在t1完成了它的第一个工作想要获取obj2的锁。它必须等到t2完成obj2。但是t2正在等待t3完成并从obj3释放锁定。另一方面,如果t3已经锁定了被t1阻塞的obj1,则只会释放来自obj3的锁。
所以每个人都在等待另一个人完成。这基本上是具有三个线程的死锁的定义。
您可以在输出中看到这一点:
t1 acquiring lock on java.lang.Object@78f92cc8
t1 acquired lock on java.lang.Object@78f92cc8
t2 acquiring lock on java.lang.Object@55d2162c
t2 acquired lock on java.lang.Object@55d2162c
t3 acquiring lock on java.lang.Object@47122d
t3 acquired lock on java.lang.Object@47122d
t1 acquiring lock on java.lang.Object@55d2162c (<-- waiting for t2 to finish)
t2 acquiring lock on java.lang.Object@47122d (<--waiting for t3 to finish)
t3 acquiring lock on java.lang.Object@78f92cc8 (<-- waiting for t1 to finish)
希望我能帮助你。
此致 克里斯