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");
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...