这是我对“哲学家晚餐”并发问题的实现。我只为两个线程工作,而其余的则遭受饥饿;)如果您能找到导致它的原因,我将不胜感激。

这是输出:

Philosopher 2 is eating
Philosopher 0 is eating
Philosopher 2 is eating
Philosopher 0 is eating
Philosopher 2 is eating
Philosopher 0 is eating
Philosopher 2 is eating
Philosopher 0 is eating
Philosopher 2 is eating
Philosopher 2 is eating
Philosopher 0 is eating
Philosopher 2 is eating
Philosopher 0 is eating

这是代码:
public class PhilosophersDinner {

    public static void main(String[] args) {
        Chopstick2[] chopsticks = new Chopstick2[5];
        Philosopher [] philosophers = new Philosopher[5];

        for (int i = 0; i < 5; i++) {
            Chopstick2 stick = new Chopstick2();
            chopsticks[i] = stick;
        }

        for (int i = 0; i < 5; i++) {
            Philosopher philo = new Philosopher(chopsticks[i] , chopsticks[(i+1)%5], i+"");
            philosophers[i] = philo;
        }

        for (int i = 0; i < philosophers.length; i++) {
            new Thread(philosophers[i]).start();
        }
    }

}

class Philosopher implements Runnable {

    private final Chopstick2 left;
    private final Chopstick2 right;
    private final String id;

    public Philosopher(Chopstick2 l, Chopstick2 r, String id){
        this.left = l;
        this.right = r;
        this.id = id;
    }

    public void eat(){
        if (left.pickUp()) {
            if (right.pickUp()) {
                chew();
                putDown();
            } else left.putDown();
        }
    }


    public void run(){
        for (int i = 0; i < 10; i++) {
            eat();
        }
    }

    public void chew(){
        try {
            System.out.println("Philosopher "+id+" is eating");
            Thread.sleep(400);
        } catch (InterruptedException e) {
            e.printStackTrace();
            // release lock here?
        }
    }

    public void putDown(){
        left.putDown();
        right.putDown();
    }

}

class Chopstick2 {
    private volatile boolean taken = false;

    public synchronized boolean pickUp(){
        if (!taken) {
            taken = true;
            return true;
        }
        else return false;
    }

    public synchronized void putDown(){
        taken = false;
    }
}

最佳答案

问题在于,前两个拿筷子的Philosophers花费了半秒的进餐时间,在此期间,其他三名食客尝试进食直到他们放弃并戒烟为止。

一种解决方案是让所有哲学家都在指定的时间内进食,而不是进行特定数量的进食尝试。

    for (long i = System.currentTimeMillis()+10000; i > System.currentTimeMillis(); ) {
        eat();
    }

关于java - 进餐哲学家守则中发生的饥饿,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17257018/

10-09 04:12