java - 使用正确的ExecutorService异步执行任务

标签 java asynchronous concurrency threadpool executorservice

在处理一项任务时,我必须处理 2 个子任务(基本上是步骤),这些子任务可以异步完成。

我创建了 Executors.newSingleThreadExecutor() 并调用它执行两次。由于它是单线程池,这是否意味着第二个子任务(即下面代码中的步骤 5)将串行执行,即仅在步骤 3 完成后执行。我是否需要实例化 Executors.newFixedThreadExecutor(2) - 以 2 作为参数,因为我只需要异步执行两个步骤,或者还应该做什么。

public class MyTaskImpl
{
private static final ExecutorService JOB_EXEC_SVC = Executors.newSingleThreadExecutor();

public void doTask() throws Exception
    {
      // step 1
      // step 2
      // step 3 execute ASYNC
JOB_EXEC_SVC.execute(() -> step3(param1, param2));
      // step 4
      // step 5 execute ASYNC
JOB_EXEC_SVC.execute(() -> step5(param));
      // step 6
    }
}

最佳答案

你是对的。由于您使用的 ExecutorService 是使用 newSingleThreadExecutor 创建的,因此步骤 5 将在步骤 3 完成后完成。为了异步执行这两个操作,请使用 newFixedThreadExecutor:

public class MyTaskImpl {

    private static final ExecutorService JOB_EXEC_SVC = Executors.newFixedThreadExecutor(2);

    public void doTask() throws Exception {
        // Step 1
        // Step 2
        // Step 3 (below)
        JOB_EXEC_SVC.execute(() -> step3(param1, param2));
        // Step 4
        // Step 5 (below)
        JOB_EXEC_SVC.execute(() -> step5(param));
    }
}

但这并不能保证步骤 3 和步骤 5 将并行执行。例如,如果步骤 4 需要很长时间才能完成,则可以在步骤 3 执行完成后将步骤 5 提交给 ExecutorService(即调用execute)。

对于单线程情况也是如此,但无论步骤 4 花费的时间如何,步骤 5 总是会在步骤 3 完成后执行(但不确定步骤 5 是否在步骤 3 运行时提交并阻塞)直到步骤 3 完成,或者如果步骤 5 在步骤 3 完成后提交)。

关于java - 使用正确的ExecutorService异步执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54041534/

相关文章:

java - 类 Arrays 中重载方法 sort 的意义是什么

java - 等待 Java 线程池中的线程子集

java - @Async 在 REST 类中不起作用

python - 将 Matplotlib 与 Django 结合使用

scala - 在 Scala 中实现 Go 的并发模式难吗?

java - UnsatisfiedLInkError Eclipse JNI(从命令行工作但不在 Eclipse 中工作)包名称

java - 未在包含 JTable 的 JScrollPane 中调用 TableModel

java - 将文件读取为字符串并

javascript - async.waterfall 不会在最后呈现

Javascript Promise 链问题 (Ember)