2011-01-09 237 views
25

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

说你有这两种方法的类:

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

你会如何实现同步doSomething()不返回,直到任务完成?

回答

63

看看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与两方这样相同的行为:

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

+1感谢您的详细解答,rodion! – hpique 2011-01-09 15:30:22