【问题标题】:Java asynchronous method callJava异步方法调用
【发布时间】:2011-04-29 13:49:26
【问题描述】:

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

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 的方式,但没有运气。天呐

【问题讨论】:

    标签: java asynchronous methods call


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      猜你喜欢
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2015-11-28
      相关资源
      最近更新 更多