我有一个只支持异步执行某些操作的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);
}
}
上面使用的条件是这种情况的最佳解决方案吗?
答案 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);
}
}