五哲学家进餐问题java
时间: 2023-11-13 19:54:51 浏览: 97
五哲学家进餐问题是一个经典的并发编程问题,涉及到多个线程之间的同步和资源竞争。问题描述如下:五个哲学家围坐在一张圆桌前,每个哲学家面前有一碗饭和一只筷子。哲学家的生活方式非常奇特,他们交替进行思考和进餐。当一个哲学家思考时,他会放下他的两只筷子,但是当他想要进餐时,他必须同时拿起他左右两边的筷子才能吃到饭。问题在于如何避免死锁和饥饿的情况发生。
解决方案:
1. 给每个哲学家分配一个编号,编号为奇数的哲学家先拿起左边的筷子再拿右边的筷子,编号为偶数的哲学家先拿起右边的筷子再拿左边的筷子。
2. 引入一个服务员,服务员控制每个哲学家拿筷子的顺序,避免死锁和饥饿的情况发生。
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) {
//思考
System.out.println("Philosopher " + id + " is thinking.");
Thread.sleep((int) (Math.random() * 100));
//拿起左边的筷子
synchronized (leftChopstick) {
System.out.println("Philosopher " + id + " picked up left chopstick.");
//拿起右边的筷子
synchronized (rightChopstick) {
System.out.println("Philosopher " + id + " picked up right chopstick and is eating.");
//进餐
Thread.sleep((int) (Math.random() * 100));
System.out.println("Philosopher " + id + " put down right chopstick.");
}
//放下左边的筷子
System.out.println("Philosopher " + id + " put down left chopstick.");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class DiningPhilosophers {
public static void main(String[] args) {
Philosopher[] philosophers = new Philosopher[5];
Object[] chopsticks = new Object[5];
for (int i = 0; i < 5; i++) {
chopsticks[i] = new Object();
}
for (int i = 0; i < 5; i++) {
Object leftChopstick = chopsticks[i];
Object rightChopstick = chopsticks[(i + 1) % 5];
if (i == 4) {
philosophers[i] = new Philosopher(i, rightChopstick, leftChopstick);
} else {
philosophers[i] = new Philosopher(i, leftChopstick, rightChopstick);
}
new Thread(philosophers[i]).start();
}
}
}
```
阅读全文