发生Deadlock的情况:
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
输出结果:
Thread 1: locked resource 1
Thread 2: locked resource 2
叙述:发生了死锁。Thread1先获得resource1的lock,Thread2先获得resource2的lock。在Thread1还没有将resource1的lock交出时,又等着去获得resource2的lock(因为关于resource2的语句嵌套在关于resource1的语句中);同样,在Thread2还没有将resource2的lock交出时,又等着去获得resource1的lock(因为关于resource1的语句嵌套在关于resource2的语句中)。因此陷入了Deadlock
如果这样做,就不会发生Deadlock了:
(此代码并不是预防死锁的代码,只是上面的一个例子的对照)
public class TestDeadLockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
};
t1.start();
t2.start();
}
}
输出结果:
Thread 1: locked resource 1
Thread 2: locked resource 2
Thread 2: locked resource 1
Thread 1: locked resource 2
此时,获得lock1的前提并不是获得lock2了。