两个线程互相持有对方需要的锁,就会发生死锁的现象;
发生死锁后中断无效;
看一个例子
public class DeadLock {
public synchronized void show(DeadLock d){
try {
System.out.println(Thread.currentThread().getName()+":"+"show方法start");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+":"+"准备进入方法log");
d.log();
System.out.println(Thread.currentThread().getName()+":"+"show方法end");
} catch (InterruptedException e) {
}
}
public synchronized void log(){
try {
System.out.println(Thread.currentThread().getName()+":"+"log方法start");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+":"+"log方法end");
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
final DeadLock dl1 = new DeadLock();
final DeadLock dl2 = new DeadLock();
Thread t0 = new Thread(new Runnable() {
public void run() {
dl1.show(dl2);
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
dl2.show(dl1);
}
});
t0.start();
t1.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
t0.interrupt();
System.out.println("打断t0");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
System.out.println("打断t1");
t1.interrupt();
}
}
运行的结果:
Thread-0:show方法start
Thread-1:show方法start
Thread-1:准备进入方法log
Thread-0:准备进入方法log
打断t0
打断t1
此时,主线程还是运行状态的;
可以通过打印堆栈信息发现死锁;
查看该死锁的java程序,打印堆栈:
直接拉到最后即可看见死锁的信息;
对于死锁,最好在设计层面进行规避;