java Java异步方法调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4004031/
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
Java asynchronous method call
提问by vale4674
I have already one thread that has to do following work:
我已经有一个线程必须完成以下工作:
public class DetectionHandler extends TimerTask {
@Override
public void run() {
bluetoothAddresses = BluetoothModule.scanAddresses();
wiFiAddresses = WiFiModule.scanAddresses();
...//when scanning is finished, continue work
}
I would like that scanning to be parallel. So I assume that I have to call that two methods asynchronously. And when that scanning is finished, then I can continue work in DetectionHandler class.
我希望扫描是平行的。所以我假设我必须异步调用这两个方法。当扫描完成后,我可以继续在 DetectionHandler 类中工作。
I've tried the way that BluetoothModule and WiFiModule implements Runnable but had no luck. Tnx
我已经尝试过 BluetoothModule 和 WiFiModule 实现 Runnable 的方式,但没有运气。田纳西州
回答by Eugene Kuleshov
Using ExecutorServiceyou can write something like this:
使用ExecutorService你可以这样写:
ArrayList<Callable<Collection<Address>>> tasks = new ArrayList<Callable<Collection<Address>>>();
tasks.add(new Callable<Collection<Address>>() {
public Collection<Address> call() throws Exception {
return BluetoothModule.scanAddresses();
}
});
tasks.add(new Callable<Collection<Address>>() {
public Collection<Address> call() throws Exception {
return WiFiModule.scanAddresses();
}
});
ExecutorService executorService = Executors.newFixedThreadPool(2);
List<Future<Collection<Address>>> futures = executorService.invokeAll(tasks);
回答by extraneon
Get an ExecutorService from Executorsand give it a FutureTask.
从Executors获取一个 ExecutorService并给它一个FutureTask。
You can then wait for the results by calling the blocking get() on the returned Future. The scans will run parallel but your run method (shown here) will still wait for the scans to be finished.
然后,您可以通过在返回的 Future 上调用阻塞 get() 来等待结果。扫描将并行运行,但您的运行方法(此处显示)仍将等待扫描完成。
A bit like:
有一点像:
FutureTask<List<Address>> btFuture =
new FutureTask<List<Address>>(new Callable<List<Address>>() {
public List<Address> call() {
return BluetoothModule.scanAddresses();
}});
executor.execute(btFuture);
FutureTask<List<Address>> wfFuture =
new FutureTask<List<Address>>(new Callable<List<Address>>() {
public List<Address> call() {
return WifiModule.scanAddresses();
}});
executor.execute(wfFuture);
btAddresses = btFuture.get(); // blocks until process finished
wifiAddresses = wfFuture.get(); // blocks
Be carefull though, get will return whatever call returns. Exceptions are wrapped in an ExecutionException.
不过要小心,无论调用返回什么,get 都会返回。异常被包装在一个 ExecutionException 中。