我正在尝试学习餐厅哲学家问题中Semaphore的基本要点。现在,我有一个Chopstick类的数组,每个Chopstick都有一个可用许可的信号量:
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();
}
}
程序可以编译和运行,但是似乎在释放筷子时出现了一些问题。有时候,筷子会被释放,有时候则不会。当所有的筷子都被拿走且一个哲学家感到饥饿时,程序最终会挂起。
以下是哲学家类中释放筷子的代码,该代码会在随机时间后释放筷子:
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已经完成用餐",例如,并且继续执行。其他两行从未输出,所以显然我释放的方式有问题。
非常感谢您的帮助。