同步版本的异步方法

在Java中创建异步方法的同步版本的最佳方法是什么?

假设你有一个使用这两种方法的类:

asyncDoSomething(); // Starts an asynchronous task onFinishDoSomething(); // Called when the task is finished 

如何实现在任务完成之前不返回的同步doSomething()

看看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 asynchronousMain(){ asyncDoSomethig(); //ignore the return result } void synchronousMain() throws Exception{ Future f = asyncDoSomething(); //wait synchronously for result f.get(); }