gpt4 book ai didi

java - java oracle 教程中带有锁对象的 Bow/Bower 示例

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:48 24 4
gpt4 key购买 nike

在 java 文档示例中,lock.unlock()方法使用了两次,一次是在 impendingBow() 方法中,一次是在 Bow() 方法中。我的问题是,不应该lock.unlock() impendingBow()中的方法方法可以解决问题,为什么在 bow() 中再次使用它方法?下面的代码是来自 java 文档的片段:

public class Safelock {
static class Friend {
private final String name;
private final Lock lock = new ReentrantLock();

public Friend(String name) {
this.name = name;
}

public String getName() {
return this.name;
}

public boolean impendingBow(Friend bower) {
Boolean myLock = false;
Boolean yourLock = false;
try {
myLock = lock.tryLock();
yourLock = bower.lock.tryLock();
} finally {
if (! (myLock && yourLock)) {
if (myLock) {
lock.unlock();
}
if (yourLock) {
bower.lock.unlock();
}
}
}
return myLock && yourLock;
}

public void bow(Friend bower) {
if (impendingBow(bower)) {
try {
System.out.format("%s: %s has"
+ " bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
} finally {
lock.unlock();
bower.lock.unlock();
}
} else {
System.out.format("%s: %s started"
+ " to bow to me, but saw that"
+ " I was already bowing to"
+ " him.%n",
this.name, bower.getName());
}
}

}

最佳答案

shouldn't lock.unlock() method in impendingBow() method do the trick, why use it again in bow() method?

impendingBow 中,当两次锁定尝试都成功时,将无法到达 lock.unlock()。该方法返回true,使两个锁都处于锁定状态。请参阅解锁调用之前的条件语句。在这种情况下(两个锁都成功),bow() 必须解锁锁。

关于java - java oracle 教程中带有锁对象的 Bow/Bower 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52734243/

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