gpt4 book ai didi

Java异步方法调用

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:35:00 26 4
gpt4 key购买 nike

我已经有一个线程必须完成以下工作:

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 的方式,但没有成功。发送

最佳答案

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

关于Java异步方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4004031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com