死鎖發生於多線程互相持有對方需要的鎖,並等待對方釋放,形成循環等待。四個必要條件(Coffman 條件):
/**
* Java線程:並發協作-死鎖
* @author Administrator
*/
public class Test {
public static void main(String[] args) {
DeadlockRisk dead = new DeadlockRisk();
new MyThread(dead, 1, 2).start();
new MyThread(dead, 3, 4).start();
new MyThread(dead, 5, 6).start();
new MyThread(dead, 7, 8).start();
}
}
class MyThread extends Thread {
private DeadlockRisk dead; private int a, b;
MyThread(DeadlockRisk dead, int a, int b) { this.dead = dead; this.a = a; this.b = b; }
@Override public void run() { dead.read(); dead.write(a, b); }
}
class DeadlockRisk {
private static class Resource { public int value; }
private Resource resourceA = new Resource();
private Resource resourceB = new Resource();
public int read() {
synchronized (resourceA) {
System.out.println("read():" + Thread.currentThread().getName() + "獲取了resourceA的鎖!");
synchronized (resourceB) {
System.out.println("read():" + Thread.currentThread().getName() + "獲取了resourceB的鎖!");
return resourceB.value + resourceA.value;
}
}
}
public void write(int a, int b) {
synchronized (resourceB) { // 反序獲取鎖!
System.out.println("write():" + Thread.currentThread().getName() + "獲取了resourceB的鎖!");
synchronized (resourceA) {
System.out.println("write():" + Thread.currentThread().getName() + "獲取了resourceA的鎖!");
resourceA.value = a; resourceB.value = b;
}
}
}
}

程序卡住,無法繼續執行,控制台無新輸出。典型線程狀態:
ReentrantLock.tryLock(timeout) 避免無限等待// 修正:read 和 write 都按 resourceA → resourceB 順序獲取鎖
public int read() {
synchronized (resourceA) {
synchronized (resourceB) { ... }
}
}
public void write(int a, int b) {
synchronized (resourceA) { // 改為先鎖 A
synchronized (resourceB) { ... }
}
}