gpt4 book ai didi

concurrency - 活锁的好例子?

转载 作者:行者123 更新时间:2023-12-03 04:26:53 28 4
gpt4 key购买 nike

我明白什么是活锁,但我想知道是否有人有一个很好的基于代码的示例?通过基于代码,我并不是指“两个人试图在走廊里超越对方”。如果我再读一遍,我就会失去午餐。

最佳答案

这是一个非常简单的 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();
}
}

运行程序,你会得到:

Bob: You eat first my darling Alice!
Alice: You eat first my darling Bob!
Bob: You eat first my darling Alice!
Alice: You eat first my darling Bob!
Bob: You eat first my darling Alice!
Alice: You eat first my darling Bob!
...

如果不间断的话,这将永远持续下去。这是一个活锁,因为 Alice 和 Bob 都在无限循环中反复要求对方先走(因此live)。在死锁情况下,Alice 和 Bob 都会被卡住,等待对方先走——除了等待之外,他们不会做任何事情(因此死了)。

关于concurrency - 活锁的好例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1036364/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com