实现死锁的思路很简单:
1、首先要有两个资源1和2,有两个线程A和B。
2、线程A抢到了资源1,线程B抢到了资源2。
3、同时,线程A想要资源2,他要等待线程B放弃手里的资源2;线程B想要资源1,他要等待线程A放弃手里的资源1,这个时候就形成死锁了。
public class Main {
public static void main(String[] args) {
//两个资源
Object a = new Object();
Object b = new Object();
//一个线程
new Thread(() -> {
//先去拿a
synchronized (a){
System.out.println(Thread.currentThread().getName() + ": i got a!");
//睡两秒,保证另一个线程能抢到另一个资源
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//再去拿b
synchronized (b){
System.out.println(Thread.currentThread().getName() + ": i got b!");
}
}
}).start();
//另一个线程
new Thread(()->{
//先去拿b
synchronized (b){
System.out.println(Thread.currentThread().getName() + ": i got b!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//再去拿a
synchronized (a){
System.out.println(Thread.currentThread().getName() + ": i got a!");
}
}
}).start();
}
}