多线程死锁发生的原因
死锁怎么发生的呢?
死锁大致的原因就是锁A中套了个锁B,锁B中又套了个锁A,两个锁都在那边等着对方释放锁,所以造成了死锁的原因。
下面例子就是A中有B,B中有A
package com.lilei;
public class TestDeadLock {
public static void main(String[] args) {
DeadLock dead = new DeadLock();
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 DeadLock dl;
private int a;
private int b;
public MyThread(DeadLock dl,int a,int b) {
this.dl = dl;
this.a = a;
this.b = b;
}
@Override
public void run() {
dl.read();
dl.write(a, b);
}
}
class DeadLock{
/**
* 静态内部类
* @author lilei
*
*/
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()+"获取了A的锁");
synchronized (resourceB) {
System.out.println("read():"+Thread.currentThread().getName()+"获取了B的锁");
return resourceA.value+resourceB.value;
}
}
}
public void write(int a,int b){
synchronized (resourceB) {
System.out.println("read():"+Thread.currentThread().getName()+"获取了B的锁");
synchronized (resourceA) {
System.out.println("read():"+Thread.currentThread().getName()+"获取了A的锁");
resourceA.value = a;
resourceB.value = b;
}
}
}
}