哲学家进餐问题java
时间: 2023-11-12 10:59:48 浏览: 86
哲学家进餐问题是一个经典的并发编程问题,描述了五个哲学家围坐在一张圆桌前进餐的场景,每个哲学家需要先拿起自己左右两边的筷子才能进餐,但是每次只有一根筷子可以被拿起,如果所有哲学家都拿起了自己左边的筷子,那么他们就会陷入死锁状态。解决这个问题的方法有很多,其中比较常见的是使用资源分级的方法,即让哲学家按照一定顺序拿起筷子,避免死锁的发生。
以下是一个简单的 Java 实现:
```java
public class Philosopher implements Runnable {
private int id;
private Object leftChopstick;
private Object rightChopstick;
public Philosopher(int id, Object leftChopstick, Object rightChopstick) {
this.id = id;
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
}
public void run() {
try {
while (true) {
// 拿起左边的筷子
synchronized (leftChopstick) {
System.out.println("Philosopher " + id + " picks up left chopstick");
// 拿起右边的筷子
synchronized (rightChopstick) {
System.out.println("Philosopher " + id + " picks up right chopstick and starts eating");
// 进餐
Thread.sleep(1000);
System.out.println("Philosopher " + id + " puts down right chopstick");
}
}
System.out.println("Philosopher " + id + " puts down left chopstick and thinks");
// 思考
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int numPhilosophers = 5;
Philosopher[] philosophers = new Philosopher[numPhilosophers];
Object[] chopsticks = new Object[numPhilosophers];
for (int i = 0; i < numPhilosophers; i++) {
chopsticks[i] = new Object();
}
for (int i = 0; i < numPhilosophers; i++) {
philosophers[i] = new Philosopher(i, chopsticks[i], chopsticks[(i + 1) % numPhilosophers]);
new Thread(philosophers[i]).start();
}
}
}
```
阅读全文