java ExecutorService并行运行任务并保存结果
我想同时发送最多10个用户的ping,并在ping完成后用结果更新用户对象
为了做到这一点,我试图使用ExecutorService
我从这样的代码开始:
private void pingUsers(List<User> userList) throws ExecutionException, InterruptedException {
final int NUM_THREADS = 10;
ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
for (User user : userList) {
SnmpPingDevice pingUser = new PingUser(user);
Future<Boolean> isUserActive = executor.submit(pingUser);
user.isActive = isUserActive.get() ; // -- I guess it will block other pings and i'm back to my starting point where I need to run the pings in parallel.
}
executor.shutdown();
try {
executor.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error("Failed to terminate executor");
}
}
这就是我的PingUser类的样子:
@Override
public Boolean call() {
ping = new CmdRunner(toolDir,outDir,
new UserOidWorkerPing(version,community,ip,logger));
return this.isActive();
}
public boolean isActive(){
String cmd = ping.getCmdNoRedirect();
String rc = this.cmdRunner.runShellCmd(cmd,this.outDir +"/dummy",false);
logger.debug("PING was sent with cmd:" + cmd + ",rc:" + rc);
return rc != null && !rc.contains("Timeout:") && !rc.isEmpty();
}
回到同一个问题,ping不会并行运行(只要循环等待isUserActive.get()
结束)
知道我错过了什么吗?如何使这些ping并行运行,并将结果保存到我的List<User> userList
中的每个用户
# 1 楼答案
Future::get
是一个阻塞操作,因此调用线程将被阻塞,直到调用完成。因此,只有在前一个任务完成后,才能提交新任务考虑使用{a1},它将返回一个列表^ {< CD3>}s:< /p>