我对Java很陌生,我正在努力学习生动活泼的概念。
我在网上发现了一个很好的例子,一对夫妻正在试着喝汤,但他们之间只有一个勺子。配偶双方都太客气了,如果对方还没吃东西,他们会把勺子递给对方的。
我的问题是,在这个特殊的例子中,我们应该做些什么来克服生动活泼的问题呢?我希望修改我的代码来演示这个问题的解决方案。
public class Livelock {
static class Spoon {
private Diner owner;
public Spoon(Diner d) { owner = d; }
public Diner getOwner() { return owner; }
public synchronized void setOwner(Diner d) { owner = d; }
public synchronized void use() {
System.out.printf("%s has eaten!", owner.name);
}
}
static class Diner {
private String name;
private boolean isHungry;
public Diner(String n) { name = n; isHungry = true; }
public String getName() { return name; }
public boolean isHungry() { return isHungry; }
public void eatWith(Spoon spoon, Diner spouse) {
while (isHungry) {
// Don't have the spoon, so wait patiently for spouse.
if (spoon.owner != this) {
try { Thread.sleep(1); }
catch(InterruptedException e) { continue; }
continue;
}
// If spouse is hungry, insist upon passing the spoon.
if (spouse.isHungry()) {
System.out.printf(
"%s: You eat first my darling %s!%n",
name, spouse.getName());
spoon.setOwner(spouse);
continue;
}
// Spouse wasn't hungry, so finally eat
spoon.use();
isHungry = false;
System.out.printf(
"%s: I am stuffed, my darling %s!%n",
name, spouse.getName());
spoon.setOwner(spouse);
}
}
}
public static void main(String[] args) {
final Diner husband = new Diner("Bob");
final Diner wife = new Diner("Alice");
final Spoon s = new Spoon(husband);
new Thread(new Runnable() {
public void run() { husband.eatWith(s, wife); }
}).start();
new Thread(new Runnable() {
public void run() { wife.eatWith(s, husband); }
}).start();
}
}发布于 2016-02-18 13:07:40
一般来说,没有一个通用的方法来解决生动活泼问题。
如果没有检测到进度,则线程必须停止重复相同的操作。
在你的例子中,允许配偶多吃一次(从而发现爱人没有吃过东西,而且没有进展,因为进食只需要一步)应该迫使勺子的主人只吃一次。
很明显,现实生活中的场景会更加精细,但检测零进展和采取与通常不同的行动是至关重要的。
https://stackoverflow.com/questions/35481945
复制相似问题