如何使用信号量在 Java 中编写哲学家就餐的代码?
我必须使用信号量在 Java 中编写哲学家就餐问题的解决方案。信号量是“手动”创建信号量类来完成的。看起来像这样:
package principal;
public class Semaforo {
private int valor;
private int esperando;
public Semaforo(int valor) {
this.valor=valor;
this.esperando=0;
}
public synchronized void down() {
if (this.valor >0 ){
this.valor--;
} else {
this.esperando++;
try {
wait();
} catch (Exception e) {
}
}
}
public int getValor() {
return valor;
}
public synchronized void up() {
if (this.valor > 0) {
this.valor++;
} else {
if (this.esperando >0 ) {
notify();
this.esperando--;
} else {
this.valor++;
}
}
}
}
如果我有一个解决方案可以避免死锁、饥饿、活锁等并发问题,我会很高兴。我想让每个哲学家在自己的时间吃饭,但我不知道如何用信号量来实现这一点。如何使用 Java 中的信号量解决哲学家就餐问题?
任何帮助表示赞赏。
I have to code a solution to the dining philosophers problem in Java using semaphores. The semaphore is done "by hand" creating a semaphore class. And looks like this:
package principal;
public class Semaforo {
private int valor;
private int esperando;
public Semaforo(int valor) {
this.valor=valor;
this.esperando=0;
}
public synchronized void down() {
if (this.valor >0 ){
this.valor--;
} else {
this.esperando++;
try {
wait();
} catch (Exception e) {
}
}
}
public int getValor() {
return valor;
}
public synchronized void up() {
if (this.valor > 0) {
this.valor++;
} else {
if (this.esperando >0 ) {
notify();
this.esperando--;
} else {
this.valor++;
}
}
}
}
I would be nice if I had a solution that avoids problems of concurrency like deadlocks, starvation, live-locks, and so on. I thought of having each philosopher eat at his own time, but I don't know how I could accomplish that with semaphores. How do I solve the dinning philosophers problem with semaphores in Java?
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此(第 87 页)回顾一下来自 Tanenbaum 的现代操作系统 3e 的哲学家就餐问题。这个问题是通过 C 编程语言中的信号量来解决的。
This (page 87) goes over the Dining Philosophers problem taken from Tanenbaum's Modern Operating Systems 3e. The problem is solved with sempahores in the C programming language.
您不需要 esparanto 字段,也不需要每次 up() 可用信号量的数量时检查“valor”的状态。我工作很无聊,所以我修剪了你的代码:
You don't need the esparanto field and you don't need to check the state of 'valor' every time you up() the number of available semaphores. I'm bored at work so I trimmed your code: