繁体   English   中英

ExecutorService submit() - 如何使其非阻塞?

[英]ExecutorService submit() - How to make it non blocking?

我正在尝试使以下代码非阻塞。 我正在使用 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);

然后我在该列表上循环并使用Futureget() function 来执行每个任务 - 这似乎是阻塞的:

 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方法(运行上面的所有代码)是非阻塞的,这意味着应该一个接一个地打印“开始”和“结束”打印。 我希望我的程序继续工作,尽管我的执行者运行他自己的任务。

知道如何使我的线程执行程序代码非阻塞吗?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM