具有锁定对象的Java Oracle教程中的Bow / Bower示例

时间:2018-10-10 06:49:12

标签: java multithreading concurrency locking reentrantlock

在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());
        }
    }

}

1 个答案:

答案 0 :(得分:0)

  

lock.unlock()方法中的impendingBow()方法不应该做到这一点,为什么在bow()方法中再次使用它?

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