产生死锁原因:同步嵌套
两重锁嵌套,两个线程相互等待导致
死锁代码:
MyLock.java
//生成两个要获得锁的对象
public class MyLock{
Object static objA = new Object();
Object static objB = new Object();
}
TestDeadLock.java
//死锁线程类
public class TestDeadLock implement Runnable{
private boolean flag = true;
public
TestDeadLock(boolean flag){- this.flag = flag;
- }
@Override
public void run(){
if(flag){
sychronized(MyLock.objA){
System.out,println("进入A线程锁");
sychronized(MyLock.objB){//等待B线程释放锁
System.out.println("进入A线程锁的B同步块");
}
}
}else{
sychronized(MyLock.objB){
System.out,println("进入B线程锁");
sychronized(MyLock.objA){//等待A线程释放锁
System.out.println("进入B线程锁的A同步块");
}
}
}
}
解决死锁的方法:
Java的唤醒机制-----notify()和notifyAll()方法