使用Java实现死锁
学习并发编程的死锁,之前在408的操作系统也学习过相关概念,今天使用Java代码自己实现了一下。
首先了解一下死锁的四个必要条件(发生死锁一定会发生下面四个情况):
互斥 (Mutual Exclusion): 资源一次只能被一个线程占用。 只有一个叉子或者叉子,不能两个人同时用
持有并等待 (Hold and Wait): 线程持有资源的同时,还在等待其他资源。 小明拿着勺子,还在等叉子
不可抢占 (No Preemption): 线程持有的资源不能被强行拿走。 勺子被小红拿了,不能抢
循环等待(Circular Wait): 线程形成环状等待。 小明等勺子 -> 小红等叉子 -> 小明等勺子(循环了!)
具体代码如下:
java
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DeadLock {
public static void main(String[] args) {
table table = new table();
new Thread(table::eat1, "小兰").start();
new Thread(table::eat2, "小明").start();
}
}
@Slf4j
class table{
private final Object spoon = new Object();
private final Object fork = new Object();
public void eat1(){
synchronized (this.fork){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.debug(Thread.currentThread().getName()+"先拿了fork,等待拿spoon");
synchronized (this.spoon){
log.debug(Thread.currentThread().getName()+"再拿了spoon,正在吃饭");
}
}
}
public void eat2(){
synchronized(this.spoon){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.debug(Thread.currentThread().getName()+"先拿了spoon,等待拿fork");
synchronized (this.fork){
log.debug(Thread.currentThread().getName()+"再拿了fork,正在吃饭");
}
}
}
}