java 异步方法的同步版本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4639853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sync version of async method
提问by hpique
What's the best way to make a synchronous version of an asynchronous method in Java?
在 Java 中制作异步方法的同步版本的最佳方法是什么?
Say you have a class with these two methods:
假设您有一个包含这两种方法的类:
asyncDoSomething(); // Starts an asynchronous task
onFinishDoSomething(); // Called when the task is finished
How would you implement a synchronous doSomething()
that does not return until the task is finished?
你将如何实现一个doSomething()
直到任务完成才返回的同步?
回答by rodion
Have a look at CountDownLatch. You can emulate the desired synchronous behaviour with something like this:
看看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();
}
You can also achieve the same behaviour using CyclicBarrier
with 2 parties like this:
您还可以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();
}
If you have control over the source-code of asyncDoSomething()
I would, however, recommend redesigning it to return a Future<Void>
object instead. By doing this you could easily switch between asynchronous/synchronous behaviour when needed like this:
但是,如果您可以控制asyncDoSomething()
I的源代码,则建议重新设计它以返回一个Future<Void>
对象。通过这样做,您可以在需要时轻松地在异步/同步行为之间切换,如下所示:
void asynchronousMain(){
asyncDoSomethig(); //ignore the return result
}
void synchronousMain() throws Exception{
Future<Void> f = asyncDoSomething();
//wait synchronously for result
f.get();
}