Java异步方法调用

时间:2010-10-23 12:50:57

标签: java asynchronous methods 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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

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中。