在Java中创建异步方法的同步版本的最佳方法是什么?
假设您有一个使用这两种方法的课程:
asyncDoSomething(); // Starts an asynchronous task
onFinishDoSomething(); // Called when the task is finished
如何实现在任务完成之前不会返回的同步doSomething()
?
答案 0 :(得分:67)
看看CountDownLatch。您可以使用以下内容模拟所需的同步行为:
private CountDownLatch doneSignal = new CountDownLatch(1);
void main() throws InterruptedException{
asyncDoSomething();
//wait until doneSignal.countDown() is called
doneSignal.await();
}
void onFinishDoSomething(){
//do something ...
//then signal the end of work
doneSignal.countDown();
}
你也可以使用CyclicBarrier
和2个派对来实现相同的行为:
private CyclicBarrier barrier = new CyclicBarrier(2);
void main() throws InterruptedException{
asyncDoSomething();
//wait until other party calls barrier.await()
barrier.await();
}
void onFinishDoSomething() throws InterruptedException{
//do something ...
//then signal the end of work
barrier.await();
}
如果您可以控制asyncDoSomething()
的源代码,我建议您重新设计它以返回Future<Void>
对象。通过这样做,您可以在需要时轻松切换异步/同步行为,如下所示:
void asynchronousMain(){
asyncDoSomethig(); //ignore the return result
}
void synchronousMain() throws Exception{
Future<Void> f = asyncDoSomething();
//wait synchronously for result
f.get();
}