gpt4 book ai didi

java - 在java中解决死锁的替代方法

转载 作者:行者123 更新时间:2023-11-29 05:37:15 24 4
gpt4 key购买 nike

我正在阅读 Java Concurrency Tutorial来自 Oracle。

还有一个例子 DeadLock

核心代码:

    public synchronized void bow(Friend bower) {
System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName());
bower.bowBack(this);
}

public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s" + " has bowed back to me!%n", this.name, bower.getName());
}

然后当教程转到 LockObject 时,它提供了一个处理死锁的解决方案 Lock Object .

现在我想知道是否有另一种方法可以在不使用 Lock 对象的情况下避免死锁?

最佳答案

避免死锁的一种方法是通过强加获取两个锁的顺序来打破对称性。例如,你可能会说,当开始鞠躬时,线程应该总是锁定名字按字母顺序排在第一位的 friend ,这样任何做鞠躬的线程都必须先获得 Alphonse 的锁,然后再获得 Gaston 的锁,永远不会反过来:

    public void bow(Friend bower) {
Friend lock = (this.name.compareTo(bower.name)<0)? this : bower);
synchronized (lock) {
System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName());
bower.bowBack(this);
}
}
public void bowBack(Friend bower) {
Friend lock = (this.name.compareTo(bower.name)>0)? this : bower);
synchronized (lock) {
System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName());
}
}

无锁选项使用原子变量来指示弓是否已经在进行中,如果有则等待:

    private static AtomicBoolean bowing = new AtomicBoolean();
public void bow(Friend bower) {
while (!bowing.compareAndSet(false, true)) Thread.yield();

System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName());
bower.bowBack(this);

bowing.set(false);
}

另一种避免死锁的方法是使用单个锁而不是两个;竞争同一个锁的两个线程不会死锁。

    private static Object lock = new Object();
public void bow(Friend bower) {
synchronized (lock) {
System.out.format("%s: %s has bowed to me!%n", this.name, bower.getName());
bower.bowBack(this);
}
}

public void bowBack(Friend bower) {
synchronized (lock) {
System.out.format("%s: %s has bowed back to me!%n", this.name, bower.getName());
}
}

关于java - 在java中解决死锁的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041122/

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