發生死鎖的原因一般是兩個對象的鎖相互等待造成的。
在《Java線程:線程的同步與鎖》一文中,簡述死鎖的概念與簡單例子,但是所給的例子是不完整的,這裡給出一個完整的例子。
/**
* Java線程:並發協作-死鎖
*
* @author Administrator
*/
public class Test {
public static void main(String[] args) {
DeadlockRisk dead = new DeadlockRisk();
MyThread t1 = new MyThread(dead, 1, 2);
MyThread t2 = new MyThread(dead, 3, 4);
MyThread t3 = new MyThread(dead, 5, 6);
MyThread t4 = new MyThread(dead, 7, 8);
t1.start();
t2.start();
t3.start();
t4.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() + "獲取了resourceA的鎖!");
synchronized (resourceA) {
System.out.println("write():" + Thread.currentThread().getName() + "獲取了resourceB的鎖!");
resourceA.value = a;
resourceB.value = b;
}
}
}
}
下面死鎖的情況發生了,真是難得一見啊:
出處:http://lavasoft.blog.51cto.com/62575/222074