异步方法的同步版本

2022-09-01 11:23:24

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

假设您有一个具有以下两种方法的类:

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

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


答案 1

看看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();
}

您还可以使用2个参与方来实现相同的行为,如下所示:CyclicBarrier

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();
}

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

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

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

答案 2

推荐