T1-------------T2
res A----------res B
res B----------res A
If T1 put a lock on res A, T2 put a lock on res B, then T1 tries to lock res B (waiting the lock on res B to be released) an then T2 tries to lock res A (waiting the lock put by T1 to be released). The 2 threads do not speak to each others and will wait...indefinitely... The JVM seems not able to deal with such a problem...
You have to deal with it !!!
package threaddeadlock;
public class Main implements Runnable {
ClassA refA = new ClassA();
ClassB refB = new ClassB();
void operation1() throws Exception {
synchronized (refA) {
refA.method1();
synchronized (refB) {
refB.method2();
}
}
}
void operation2() throws Exception {
synchronized (refB) {
refB.method2();
synchronized (refA) {
refA.method1();
}
}
}
public void run() {
try {
if (Thread.currentThread().getName().equals("t1")) {
operation1();
} else if (Thread.currentThread().getName().equals("t2")) {
operation2();
} else { // should be an assertion !!!
System.err.println("thread name must be t1 or t2 !!!");
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Main main = new Main();
Thread t1 = new Thread(main);
t1.setName("t1");
Thread t2 = new Thread(main);
t2.setName("t2");
t1.start();
t2.start();
}
}
wait forever in front of your screen... :-)
run:
t1 method1
t2 method2
BUILD STOPPED (total time: 13 minutes 30 seconds)
package threaddeadlock;
public class ClassA {
void method1() {
System.out.println(Thread.currentThread().getName() + " method1");
}
}
package threaddeadlock;
public class ClassB {
void method2() {
System.out.println(Thread.currentThread().getName() + " method2");
}
}
No comments:
Post a Comment