线程发生死锁可能性很小即使看似可能发生死锁的代码在运行时发生死锁的可能性也是小之又小
发生死锁的原因一般是两个对象的锁相互等待造成的
在《Java线程线程的同步与锁》一文中简述死锁的概念与简单例子但是所给的例子是不完整的这里给出一个完整的例子
/**
* Java线程并发协作死锁
*
* @author Administrator ::
*/
public class Test {
public static void main(String[] args) {
DeadlockRisk dead = new DeadlockRisk();
MyThread t = new MyThread(dead );
MyThread t = new MyThread(dead );
MyThread t = new MyThread(dead );
MyThread t = new MyThread(dead );
tstart();
tstart();
tstart();
tstart();
}
}
class MyThread extends Thread {
private DeadlockRisk dead;
private int a b;
MyThread(DeadlockRisk dead int a int b) {
thisdead = dead;
thisa = a;
thisb = b;
}
@Override
public void run() {
deadread();
deadwrite(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) {
Systemoutprintln(read(): + ThreadcurrentThread()getName() + 获取了resourceA的锁!);
synchronized (resourceB) {
Systemoutprintln(read(): + ThreadcurrentThread()getName() + 获取了resourceB的锁!);
return resourceBvalue + resourceAvalue;
}
}
}
public void write(int a int b) {
synchronized (resourceB) {
Systemoutprintln(write(): + ThreadcurrentThread()getName() + 获取了resourceA的锁!);
synchronized (resourceA) {
Systemoutprintln(write(): + ThreadcurrentThread()getName() + 获取了resourceB的锁!);
resourceAvalue = a;
resourceBvalue = b;
}
}
}
}
下面死锁的情况发生了真是难得一见啊
本文出自 熔 巖 博客请务必保留此出处