死锁
概念,AB线程,A持有a锁B持有b锁,A在等待b锁,而B在等待a锁
发生场景之一:同步嵌套
简单的嵌套造成死锁的Demo:
class Lock implements Runnable{
private boolean flag;
public Lock(boolean flag){
this.flag = flag;
}
@Override
public void run() {
if(flag){
while(true){
synchronized (LockObj.obj1) {
System.out.println(Thread.currentThread().getName()+" if...");
synchronized (LockObj.obj2) {
System.out.println(Thread.currentThread().getName()+" if...");
}
}
}
}else{
while(true){
synchronized (LockObj.obj2) {
System.out.println(Thread.currentThread().getName()+" else...");
synchronized (LockObj.obj1) {
System.out.println(Thread.currentThread().getName()+" else...");
}
}
}
}
}
public synchronized void show(){
System.out.println(Thread.currentThread().getName()+"show...");
}
}
class LockObj{
public static final Object obj1 = new Object();
public static final Object obj2 = new Object();
}
class Test{
public static void main(String[] args) {
Lock l1 = new Lock(false);
Lock l2 = new Lock(true);
Thread t1 = new Thread(l1);
Thread t2 = new Thread(l2);
t1.start();
t2.start();
}
}
这个demo我测试过了,没问题的,绝壁死锁。简单分析一下,线程t1因为flag为false所以永远走esle分支,相反的t2永远走if分支,当main线程运行到t2.start();之后,两个线程开启,假定t2先拿到cpu的执行权,走if分支拿到obj1锁,这时候有可能t1也拿到cpu的执行权拿到obj2的锁,再如果t2继续走想拿obj2锁,但此时obj2锁在t1手里,而t2也想拿obj1,这样都相互想拿对方的锁,就僵持不下造成死锁,加一个while(true)的原因是让他一定出现死锁,不然有时候试好多次,死锁的现象不明显就蛋碎了。