我正在尝试在餐饮哲学家问题中学习信号量的基本要点。现在,我有一个 Chopstick 类数组,每个 Chopstick 都有一个带有 1 个可用许可证的信号量:
public class Chopstick
{
Thread holder = null;
private Semaphore lock = new Semaphore(1);
public synchronized void take() throws InterruptedException
{
this.lock.acquire();
holder = Thread.currentThread();
}
public synchronized void release()
{
this.lock.release();
holder = null;
}
}
holder 变量用于我不确定是否需要的函数:
public synchronized void conditionalRelease()
{
if (holder == Thread.currentThread())
{
holder = null;
this.lock.release();
}
}
程序编译并运行,但似乎在释放筷子时遇到了一些麻烦。有时,筷子会松开,有时不会。当他们不释放时,程序最终会在所有筷子都被拿走并且一位哲学家饿了时挂断。
这是 Philosopher 类中的代码,用于在随机时间后释放筷子:
System.out.println(this.name + " is eating");
Thread.sleep(this.getRandTime());
System.out.println(this.name + " has finished eating");
rightChopstick.release();
System.out.println(this.name + " has released the right chopstick");
leftChopstick.release();
System.out.println(this.name + " has released the left chopstick");
例如,我的程序确实输出“哲学家 0 吃完饭”,然后继续执行。另外两行从不输出,所以很明显我发布的方式有问题。
任何帮助表示赞赏。