如何解决ExecutorService Submit-如何使其不阻塞?
我正在尝试使以下代码不受阻碍。 我正在使用ExecutorService。
在我的构造函数中:
this.executor = Executors.newFixedThreadPool(5);
executor.awaitTermination(10,TimeUnit.SECONDS);
然后将要并行运行的所有项目添加到列表中
Future<Map.Entry<Location,SomeData>> result = this.executor.submit(new Sender(entry));
resultList.add(result);
然后我在该列表上循环并使用get()
的{{1}}函数来执行每个任务-似乎正在阻塞:
Future
发件人通话():
for (int i = 0; i < resultList.size(); i++) {
Future<Map.Entry<Location,SomeData>> result = resultList.get(i);
try {
logger.info("[Start] Task" + sendQueue.get(i).getKey() + "-" + i);
entry = result.get();
} catch (InterruptedException e) {
logger.error("Interrupted error",e);
} catch (ExecutionException e) {
logger.error("Thread Execution error",e);
} catch (Exception e) {
logger.error("Send Error",e);
}
if (entry == null) {
logger.error("Telemetry Send Error");
return;
}
logger.info("[Success] Task" + entry.getKey() + "-" + i);
}
然后我的程序在以下位置运行所有这些代码:
@Override
public Map.Entry<Location,Data> call() throws InterruptedException {
Thread.sleep(5000);
return this.entry;
}
我希望public void myMainProgram() {
System.out.println("Started");
this.startAllExecutorTasks();
System.out.println("Ended - More code that should run without waiting for the tasks");
}
方法(运行上面的所有代码)是无阻塞的,这意味着应该“开始”和“结束”打印一个接一个地打印。我希望我的程序可以继续运行,尽管我的执行者可以执行自己的任务。
有什么主意可以使我的线程执行程序代码不阻塞吗?
解决方法
我希望startAllExecutorTasks方法(运行上面的所有代码)是无阻塞的,这意味着“开始”和“结束”打印应该一个接一个地打印。
它被阻止的原因是因为您等待Future
的结果。
如果要使方法调用不阻塞,同时仍等待结果,请在后台线程中进行方法调用:
void startAllExecutorTasksInBackground() {
Executors.newSingleThreadExecutor()
.submit(this::startAllExecutorTasks);
}
public void myMainProgram() {
System.out.println("Started");
this.startAllExecutorTasksInBackground();
System.out.println("Ended - More code that should run without waiting for the tasks");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。