在java docs示例中,lock.unlock()
方法使用了两次,一次在impendingBow()方法和bow()方法中使用。我的问题是,lock.unlock()
方法中的impendingBow()
方法不应该解决这个问题,为什么在bow()
方法中再次使用它?下面的代码是java docs的摘录:
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());
}
}
}
答案 0 :(得分:0)
lock.unlock()
方法中的impendingBow()
方法不应该做到这一点,为什么在bow()
方法中再次使用它?
在impendingBow
中,当两次锁定尝试均成功时,将不会达到lock.unlock()
。该方法返回true
,使两个锁都处于锁定状态。在解锁调用之前,请参阅条件语句。在这种情况下(两个锁都成功),bow()
必须解锁这些锁。