面试官:手写一个必然死锁的例子
阅读本文大概需要 5 分钟。
来自:blog.csdn.net/xiewenfeng520/article/details/107230996
前言
什么是死锁? 死锁有什么危害和特点? 代码实现一个必然死锁的示例 分析死锁的过程
推荐下自己做的 Spring Boot 的实战项目: https://github.com/YunaiV/ruoyi-vue-pro
项目环境
jdk 1.8
github 地址:https://github.com/huajiexiewenfeng/java-concurrent
本章模块:deadlock
推荐下自己做的 Spring Cloud 的实战项目: https://github.com/YunaiV/onemall
1.什么是死锁?
关键词:并发场景,多线程
关键词:互不相让
2.死锁的影响和危害
2.1 死锁的影响
2.1.1 数据库中
2.1.2 JVM 中
2.2 死锁的危害以及特点
关键词:概率性事件
关键词:危害大,发生几率不高
3.必然死锁示例
public class MustDeadLockDemo {
public static void main(String[] args) {
Object lock1 = new Object();
Object lock2 = new Object();
new Thread(new DeadLockTask(lock1, lock2, true), "线程1").start();
new Thread(new DeadLockTask(lock1, lock2, false), "线程2").start();
}
static class DeadLockTask implements Runnable {
private boolean flag;
private Object lock1;
private Object lock2;
public DeadLockTask(Object lock1, Object lock2, boolean flag) {
this.lock1 = lock1;
this.lock2 = lock2;
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + "->拿到锁1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "->等待锁2释放...");
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + "->拿到锁2");
}
}
}
if (!flag) {
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + "->拿到锁2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "->等待锁1释放...");
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + "->拿到锁1");
}
}
}
}
}
}