不同的线程分别占用对方需要的同步资源(监听器)不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的阻塞
/**
* 死锁演示
* @author lg
* @date 2020-11-18 09:46
*/
public class ThreadTest05 {
public static void main(String[] args) {
String s1="同步监听器1";
String s2="同步监听器2";
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s1){
//...
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//同步监听器2被其他线程占用
//....
synchronized (s2){
System.out.println(Thread.currentThread().getName());
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2){
//...
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//同步监听器1被其他线程占用
//....
synchronized (s1){
System.out.println(Thread.currentThread().getName());
}
}
}
}).start();
}
}
程序不会报错,也不会停止运行