使用java语言解决哲学家就餐问题
时间: 2023-09-05 10:07:43 浏览: 106
哲学家就餐问题可以使用Java语言通过线程控制来实现。
具体实现如下:
1. 定义一个Chopstick类表示筷子,其中包含一个标识唯一性的id属性。
```
class Chopstick {
private int id;
public Chopstick(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
```
2. 定义一个Philosopher类表示哲学家,其中包含一个标识唯一性的id属性和两只筷子属性,表示他需要用到的两只筷子。
```
class Philosopher implements Runnable {
private int id;
private Chopstick leftChopstick;
private Chopstick rightChopstick;
public Philosopher(int id, Chopstick leftChopstick, Chopstick rightChopstick) {
this.id = id;
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
}
@Override
public void run() {
try {
while (true) {
// 哲学家思考
think();
// 哲学家拿起左边的筷子
synchronized (leftChopstick) {
System.out.println("Philosopher " + id + " picked up " + leftChopstick.getId() + " chopstick.");
// 哲学家拿起右边的筷子
synchronized (rightChopstick) {
System.out.println("Philosopher " + id + " picked up " + rightChopstick.getId() + " chopstick.");
// 哲学家就餐
eat();
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void think() throws InterruptedException {
System.out.println("Philosopher " + id + " is thinking.");
Thread.sleep(new Random().nextInt(1000));
}
private void eat() throws InterruptedException {
System.out.println("Philosopher " + id + " is eating.");
Thread.sleep(new Random().nextInt(1000));
System.out.println("Philosopher " + id + " put down " + rightChopstick.getId() + " chopstick.");
System.out.println("Philosopher " + id + " put down " + leftChopstick.getId() + " chopstick.");
}
}
```
3. 在main方法中创建五个哲学家和五只筷子,并启动每个哲学家的线程。
```
public class DiningPhilosophers {
public static void main(String[] args) {
Chopstick chopstick1 = new Chopstick(1);
Chopstick chopstick2 = new Chopstick(2);
Chopstick chopstick3 = new Chopstick(3);
Chopstick chopstick4 = new Chopstick(4);
Chopstick chopstick5 = new Chopstick(5);
Philosopher philosopher1 = new Philosopher(1, chopstick1, chopstick2);
Philosopher philosopher2 = new Philosopher(2, chopstick2, chopstick3);
Philosopher philosopher3 = new Philosopher(3, chopstick3, chopstick4);
Philosopher philosopher4 = new Philosopher(4, chopstick4, chopstick5);
Philosopher philosopher5 = new Philosopher(5, chopstick5, chopstick1);
new Thread(philosopher1).start();
new Thread(philosopher2).start();
new Thread(philosopher3).start();
new Thread(philosopher4).start();
new Thread(philosopher5).start();
}
}
```
在程序运行时,哲学家们会不断地思考、拿起筷子、就餐和放下筷子,直到程序被手动终止。
阅读全文