强制异步操作​​阻止当前线程

时间:2017-06-07 00:47:32

标签: java concurrency

我有一个只支持异步执行某些操作的API,我想强制它阻止我的线程。

static void doWorkSync(Worker worker) {
  final Condition condition = new ReentrantLock().newCondition();
  worker.doWorkAsync(() -> condition.signal());
  try {
    condition.await();
  } catch (InterruptedException e) {
    throw new AssertionError(e);
  }
}

上面使用的条件是这种情况的最佳解决方案吗?

1 个答案:

答案 0 :(得分:0)

CountDownLatch正是您正在寻找的!

static void doWorkSync(Worker worker) {
  final CountDownLatch latch = new CountDownLatch(1);
  worker.doWorkAsync(() -> latch.countDown());
  try {
    latch.await();
  } catch (InterruptedException e) {
    throw new AssertionError(e);
  }
}