如何等待 Java 中另一个线程中的锁被释放?

How to wait until a lock is released in another thread in Java?

我想弄清楚我们如何才能正确地等到另一个线程中的锁被释放。

我认为代码会更好地解释我的意思:

myLock.lock();
sendSomewhereMyLock(myLock); //creates new threads inside
myLock.waitUntilReleasedByAnotherThread(60L, TimeUnit.SECONDS);
//do something after the lock is released

我认为 tryLock(long time, TimeUnit unit) 是我需要的方法,但是 Java 文档说该方法将立即执行,因为锁已被当前线程获取:

If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:

  • The lock is acquired by the current thread; or
  • Some other thread interrupts the current thread, and interruption of lock acquisition is supported; or
  • The specified waiting time elapses

那我应该用什么?

我建议 CountDownLatch,它正是为此目的而设计的:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

用法示例:

CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
    doSomething();
    latch.countDown(); // Reaches 0, latch is released
}).start();
latch.await(60L, TimeUnit.SECONDS);

我想你要找的是 Condition

有了它,您可以定义一个条件,如 workCompleted,并让初始线程检查并等待该条件。

final Condition workCompleted = myLock.newCondition();
//...
myLock.lock();
try {
  final OtherThread otherThread = startOtherThread(myLock, workCompleted);
  while (otherThread.completed() == false) {
    workCompleted.await();
  }
} finally {
  myLock.unlock();
}

// other thread
doTheWork();
this.completed = true;
theLock.lock();
try {
  workCompleted.signal();
} finally {
  theLock.unlock();
}

concurrent package中有几个这样的条件,其中一些可能比上面的简单示例更符合您的要求。