public class DeadLock {
public static void main(String[] args) {
Object resource1 = new Object();
Object resource2 = new Object();
SharedObject s = new SharedObject(resource1, resource2);
TestThread11 t1 = new TestThread11(s);
TestThread22 t2 = new TestThread22(s);
t1.start();
t2.start();
}
}
class SharedObject {
Object o1, o2;
SharedObject(Object o1, Object o2) {
this.o1 = o1;
this.o2 = o2;
}
void m1() {
synchronized(o1) {
System.out.println("locked on o1 from m1()");
synchronized(o2) {
System.out.println("locked on o2 from m1()");
}
}
}
void m2() {
synchronized(o2) {
System.out.println("locked on o2 from m2()");
synchronized(o1) {
System.out.println("locked on o1 from m2()");
}
}
}
}
class TestThread11 extends Thread {
SharedObject s;
TestThread11(SharedObject s) {
this.s = s;
}
public void run() {
s.m1();
}
}
class TestThread22 extends Thread {
SharedObject s;
TestThread22(SharedObject s) {
this.s = s;
}
public void run() {
s.m2();
}
}