繁体   English   中英

Java异步方法调用

[英]Java asynchronous method call

我已经有一个线程需要做以下工作:

public class DetectionHandler extends TimerTask {

@Override
public void run() {
bluetoothAddresses = BluetoothModule.scanAddresses();
wiFiAddresses = WiFiModule.scanAddresses();
...//when scanning is finished, continue work
}

我希望扫描是平行的。 所以我假设我必须异步调用这两个方法。 当扫描完成后,我可以继续在DetectionHandler类中工作。

我已经尝试过BluetoothModule和WiFiModule实现Runnable但没有运气的方式。 TNX

使用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);

Executors获取ExecutorService并为其提供FutureTask

然后,您可以通过在返回的Future上调用阻塞get()来等待结果。 扫描将并行运行,但您的运行方法(此处显示)仍将等待扫描完成。

有一点像:

     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

但要小心,get将返回任何调用返回。 异常包含在ExecutionException中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM