3

这是我对哲学家晚餐并发问题的实现。我只为两个线程工作,其余的线程从字面上看是饥饿的;)如果您能找到它的原因,我将不胜感激。

这是输出:

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;
    }
}
4

1 回答 1

1

问题是前两个Philosophers拿到筷子的人要花半秒钟的时间吃东西,而在那段时间里,其他三个食客试图吃东西,直到他们放弃并退出。

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

    for (long i = System.currentTimeMillis()+10000; i > System.currentTimeMillis(); ) {
        eat();
    }
于 2013-06-23T01:57:49.747 回答