同步版本的异步方法

hpi*_*que 29 java asynchronous synchronous

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

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

asyncDoSomething(); // Starts an asynchronous task
onFinishDoSomething(); // Called when the task is finished 
Run Code Online (Sandbox Code Playgroud)

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

rod*_*ion 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();
}
Run Code Online (Sandbox Code Playgroud)

你也可以使用这样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();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您可以控制asyncDoSomething()我的源代码,则建议重新设计它以返回Future<Void>对象.通过这样做,您可以在需要时轻松切换异步/同步行为,如下所示:

void asynchronousMain(){
  asyncDoSomethig(); //ignore the return result
}

void synchronousMain() throws Exception{
  Future<Void> f = asyncDoSomething();
  //wait synchronously for result
  f.get();
}
Run Code Online (Sandbox Code Playgroud)