多个哲学家的中间都有一根筷子,哲学家左右需要一根筷子才能吃饭,怎么才能吃上饭
package com.company;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
// write your code here
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String number = bufferedReader.readLine();
Integer count = Integer.valueOf(number);
List<Chopsticks> chopsticksList = new ArrayList<>(count);
for (int i = 1; i <= count; i++) {
chopsticksList.add(new Chopsticks(i));
}
List<Philosopher> philosopherList = new ArrayList<>(count);
Philosopher philosopher;
for (int i = 0; i < count; i++) {
if (i % 2 == 0) {
philosopher = new Philosopher(i + 1, chopsticksList.get(i), chopsticksList.get(i + 1 >= count ? 0 : i + 1));
} else {
philosopher = new Philosopher(i + 1, chopsticksList.get(i + 1 >= count ? 0 : i + 1), chopsticksList.get(i));
}
philosopherList.add(philosopher) ;
}
for (int i = 0; i < count; i++) {
int index = i;
new Thread(() -> philosopherList.get(index).eat()).start();
}
}
static class Chopsticks {
private int index;
public Chopsticks(int index) {
this.index = index;
}
}
static class Philosopher {
private int index;
private Chopsticks left;
private Chopsticks right;
public Philosopher(int index, Chopsticks left, Chopsticks right) {
this.index = index;
this.left = left;
this.right = right;
}
public void eat() {
try {
synchronized(left) {
System.out.println("第" + index + "个哲学家拿到了第一个筷子");
Thread.sleep(1000);
synchronized (right) {
System.out.println("第" + index + "个哲学家拿到了第二个的筷子");
Thread.sleep(3000);
System.out.println("第" + index + "个哲学家吃完了");
}
}
} catch (Exception e) {
}
}
}
}
结果如下:
5
第1个哲学家拿到了第一个筷子
第3个哲学家拿到了第一个筷子
第5个哲学家拿到了第一个筷子
第1个哲学家拿到了第二个的筷子
第3个哲学家拿到了第二个的筷子
第3个哲学家吃完了
第1个哲学家吃完了
第2个哲学家拿到了第一个筷子
第5个哲学家拿到了第二个的筷子
第2个哲学家拿到了第二个的筷子
第5个哲学家吃完了
第4个哲学家拿到了第一个筷子
第4个哲学家拿到了第二个的筷子
第2个哲学家吃完了
第4个哲学家吃完了