我想同时向最多 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
中?
最佳答案
Future::get
是一个阻塞操作,因此调用线程将被阻塞,直到调用完成。因此,只有在前一个任务完成后,您才能提交新任务。
考虑使用ExecutorService::invokeAll
这将返回一个 Future
列表:
List<PingUser> pingUsers = userList.stream().map(PingUser::new).collect(Collectors.toList());
List<Future<Boolean>> results = executor.invokeAll(pingUsers);
关于java - ExecutorService - 并行运行任务并保存结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59927689/