3

我只是想知道这是否可以解决java中的哲学家就餐问题?

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MainClass {

public static void main(String[] args) {
    Lock forks[] = new ReentrantLock[5];

    for(int i = 0; i<5; i++){
        forks[i] = new ReentrantLock(); 
    }

    Thread p1 = new Thread(new Philosopher(forks[4], forks[0], "first"));
    Thread p2 = new Thread(new Philosopher(forks[0], forks[1], "second"));
    Thread p3 = new Thread(new Philosopher(forks[1], forks[2], "third"));
    Thread p4 = new Thread(new Philosopher(forks[2], forks[3], "fourth"));
    Thread p5 = new Thread(new Philosopher(forks[3], forks[4], "fifth"));

    p1.start();
    p2.start();
    p3.start();
    p4.start();
    p5.start(); 
  }
}

和我的哲学家班:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Philosopher implements Runnable {

Lock leftFork = new ReentrantLock();
Lock rightFork = new ReentrantLock();
String name; 

public Philosopher(Lock leftFork, Lock rightFork, String name) {
    this.leftFork = leftFork;
    this.rightFork = rightFork;
    this.name = name; 
}

@Override
public void run() {

    while(true){
    think(name);
    eat(leftFork, rightFork, name); 
    }
}

private void eat(Lock leftFork, Lock rightFork, String name){
    leftFork.lock();
    rightFork.lock(); 

    System.out.println(name + " eating...");

    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    finally{
        leftFork.unlock();
        rightFork.unlock(); 
        System.out.println(name + " done eating...");
    }
}

private void think(String name){
    System.out.println(name + " thinking...");

    try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
}

}

感觉应该有更多..代码。但是我已经运行了该程序,它完成了问题要求我解决的问题。任何时候只有两个哲学家在吃东西,否则他们在思考。

我有这个权利吗?

4

1 回答 1

2

不,这段代码不能避免死锁。

所有 5 位哲学家都有可能获得他们的左叉;然后他们都将永远等待他们的右分叉。

为了证明这一点,插入一个 brief sleep(),甚至只是一个println()between leftFork.lock()and rightFork.lock(),这应该使它大部分时间都失败。当前代码在我的系统上偶尔会失败,即使没有用额外的延迟引起它。

于 2012-10-28T01:38:55.487 回答