Log*_*man 5 java multithreading semaphore locking
我正在努力学习餐饮哲学家问题中信号量的基本要点.现在,我有一个类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;
}
}
Run Code Online (Sandbox Code Playgroud)
holder变量用于我不确定需要的函数:
public synchronized void conditionalRelease()
{
if (holder == Thread.currentThread())
{
holder = null;
this.lock.release();
}
}
Run Code Online (Sandbox Code Playgroud)
该程序编译并运行,但似乎在释放筷子时遇到一些麻烦.有时,筷子会被释放,有时则不会.当他们不释放时,当所有的筷子被拿走并且一个哲学家饿了时,程序最终会挂断.
这是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");
Run Code Online (Sandbox Code Playgroud)
例如,我的程序输出"Philosopher 0吃完了",并继续执行.其他两行从不输出,所以我发布的方式显然有些不对劲.
任何帮助表示赞赏.
我会从你的方法签名中取出'synchronized'关键字.您正在使用外部锁定机制(在本例中为信号量).'synchronized'关键字试图使用对象自己的互斥锁来获取锁.您现在锁定了2个我怀疑可能导致死锁的资源.
| 归档时间: |
|
| 查看次数: |
7200 次 |
| 最近记录: |