餐饮哲学家爪哇替代解决方案



我在一本书上找到了"餐饮哲学家问题"的替代解决方案,在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();
}       
}
}

让我们有 3位哲学家-P1,P2,P3和3根筷子c1,c2,c3(筷子索引等于number(

然后创建 P1(C1, C2(, P2(C2, C3(, P3(C1, C3(

最坏情况:

  • P1 在 C1 上获取锁定
  • 同时 P2 获取 C2 上的锁定 ->块 P1
  • P3 被 P1 阻挡(仍然持有 C1 锁(-> P2 可以自由获取 C3
  • P2 收购 C3 -> 饰面并发布 C2 和 C3
  • P1 获得 C2 -> 饰面并释放 C1 和 C2
  • P3 获得 C1 和 C3 -> 饰面并发布 C1 和 C3

相关内容

最新更新