异步方法的同步版本 [英] Sync version of async method

查看:154
本文介绍了异步方法的同步版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是做一个异步方法的同步版本在Java中的最佳方式?

What's the best way to make a synchronous version of an asynchronous method in Java?

假设你有这两种方法的类:

Say you have a class with these two methods:

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

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

How would you implement a synchronous doSomething() that does not return until the task is finished?

推荐答案

在看一看<一个href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html\">CountDownLatch.你可以用这样的模拟所需的同步行为:

Have a look at CountDownLatch. You can emulate the desired synchronous behaviour with something like this:

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 与两方是这样的:

You can also achieve the same behaviour using CyclicBarrier with 2 parties like this:

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

如果你有过的源 - code控制 asyncDoSomething()我会,但是,建议重新设计它返回一个未来&LT ;虚空&GT;相反对象。通过这样做,需要这样的时候,你可以很容易地异步/同步行为之间切换:

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:

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

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

这篇关于异步方法的同步版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆