30

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

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

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

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

4

1 回答 1

74

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

您还可以使用CyclicBarrier2 方来实现相同的行为,如下所示:

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()I would 的源代码,建议您重新设计它以返回一个Future<Void>对象。通过这样做,您可以在需要时轻松地在异步/同步行为之间切换,如下所示:

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

void synchronousMain() throws Exception{
  Future<Void> f = asyncDoSomething();
  //wait synchronously for result
  f.get();
}
于 2011-01-09T15:10:50.487 回答