我在书中找到了Java中“用餐哲学家问题”的替代解决方案:
public class Philosopher extends Thread {
private final int maxPause = 100;
private int bites = 10;
private Chopstick lower;
private Chopstick higher;
private int index;
public Philosopher(int i, Chopstick left, Chopstick right) {
index = i;
if (left.getNumber() < right.getNumber()) {
this.lower = left;
this.higher = right;
} else {
this.lower = right;
this.higher = left;
}
}
public void eat() {
System.out.println("Philosopher " + index + ": start eating");
pickUp();
chew();
putDown();
System.out.println("Philosopher " + index + ": done eating");
}
public void pickUp() {
pause();
lower.pickUp();
pause();
higher.pickUp();
pause();
}
public void chew() {
System.out.println("Philosopher " + index + ": eating");
pause();
}
public void pause() {
try {
int pause = AssortedMethods.randomIntInRange(0, maxPause);
Thread.sleep(pause);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void putDown() {
higher.putDown();
lower.putDown();
}
public void run() {
for (int i = 0; i < bites; i++) {
eat();
}
}
}
public class Chopstick {
private Lock lock;
private int number;
public Chopstick(int n) {
lock = new ReentrantLock();
this.number = n;
}
public void pickUp() {
lock.lock();
}
public void putDown() {
lock.unlock();
}
public int getNumber() {
return number;
}
}
解决方案的文本是:
或者,我们可以用从e到N-1的数字标记筷子。每个哲学家都尝试首先捡起编号较低的筷子。从本质上讲,这意味着每个哲学家都将左筷子放在右筷子之前(假设这就是您标记的方式),除了最后一位哲学家相反地这样做。通过这种解决方案,哲学家永远无法不握住较小的筷子而握住较大的筷子。这个 阻止具有循环能力,因为循环意味着较高的筷子会“指向”较低的筷子。
但是我不清楚。有人可以帮我举个例子吗?
谢谢
----编辑-----
主类:
public class Question {
public static int size = 3;
public static int leftOf(int i) {
return i;
}
public static int rightOf(int i) {
return (i + 1) % size;
}
public static void main(String[] args) {
Chopstick[] chopsticks = new Chopstick[size + 1];
for (int i = 0; i < size + 1; i++) {
chopsticks[i] = new Chopstick(i);
}
Philosopher[] philosophers = new Philosopher[size];
for (int i = 0; i < size; i++) {
Chopstick left = chopsticks[leftOf(i)];
Chopstick right = chopsticks[rightOf(i)];
philosophers[i] = new Philosopher(i, left, right);
}
for (int i = 0; i < size; i++) {
philosophers[i].start();
}
}
}
答案 0 :(得分:1)
有
3位哲学家-p1,p2,p3和3条筷子c1,c2,c3(筷子的索引等于number
)
您先创建p1(c1,c2),p2(c2,c3),p3(c1,c3)
最坏的情况: