Reputation: 1
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();
}
}
}
Upvotes: 0
Views: 83
Reputation: 46
You have an deadlock problem.
t1 aquires Lock for obj1. Then does some work. In the mean time t2 aquires lock for obj2 and does some work. Same goes for t3 and obj3.
Now t1 is done with its first work wants to aquire the lock of obj2. It has to wait until t2 is finished with obj2. But t2 is waiting for t3 to finish and release the lock from obj3. t3 on the other hand will only release the lock from obj3 if it has already the lock of obj1, which is blocked by t1.
So everyone is waiting for the other one to finish. This is basically the definition of a deadlock with three threads.
You can see this in your output:
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)
Hope I could help you.
Regards, Chris
Upvotes: 2