概念:
两个线程相互等待对方释放锁,造成死锁。
示例:
普通java类:
public class POJO{
Object a = new Object();
Object b = new Object();
public void a() {
synchronized(a) {
System.out.println("aaaa");
try{
Thread.sleep(2000);
} catch(InterruptedException e) {
e.printStackTrace();
}
b();
}
}
public void b() {
synchronized(b) {
System.out.println("bbbb");
try{
Thread.sleep(2000);
} catch(InterruptedException e) {
e.printStackTrace();
}
a();
}
}
}
线程A:
public class ThreadA extends Thread{
private POJO pojo;
public ThreadA(POJO pojo) {
this.pojo = pojo;
}
public void run() {
pojo.a();
}
}
线程B:
public class ThreadB extends Thread{
private POJO pojo;
public ThreadB(POJO pojo) {
this.pojo = pojo;
}
public void run() {
pojo.b();
}
}
Main方法:
public class Main{
public static void main(String[] args) {
POJO pojo = new POJO();
Thread a = new ThreadA(pojo);
a.start();
Thread b = new ThreadB(pojo);
b.start();
}
}
运行结果:
程序假死不动。
查找原因:
进入cmd,输入jps,看到如下截图,看到AppMain的id为16248:
输入jstack -l 16248,可以看出有死锁存在: