public class LockDead {
/**
* 定义两个资源对象
*/
private static final String value1 = "A";
private static final String value2 = "B";
// 主线程调用 死锁方法
public static void main(String[] args) {
new LockDead().lockDead();
}
private void lockDead() {
// 创建线程一 拥有资源A 去请求资源B
Thread thread1 = new Thread(()->{
System.out.println("我是线程一:");
while (true){
// 线程一 拿到了资源A
synchronized (value1){
System.out.println("我是线程一:拥有资源A...");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 线程一在拥有资源A的情况下 去请求资源B
synchronized (value2){
System.out.println("我是线程一:拥有资源A...现在去请求资源B");
}
}
}
});
// 线程二 拥有资源B 去请求资源A
Thread thread2 = new Thread(()->{
System.out.println("我是线程二:");
while (true) {
synchronized (value2){
System.out.println("我是线程二:拥有资源B");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 线程二在拥有资源B的情况下 去请求资源A
synchronized (value1){
System.out.println("我是线程二:拥有资源B...现在去请求资源A");
}
}
}
});
// 启动线程
thread1.start();
thread2.start();
}
}
什么 面试官竟然让你手写死锁???
最新推荐文章于 2024-06-14 15:02:13 发布