java 如何顺序执行ExecutorService中的任务?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32037844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:32:50  来源:igfitidea点击:

How to execute tasks in ExecutorService sequentially?

javamultithreadingconcurrency

提问by Raees Sharif-Aamir

I have three threads that are joined, i.e. the second thread executes after the first dies.

我有三个加入的线程,即第二个线程在第一个死后执行。

This is the code I have:

这是我的代码:

public class Main {
    public static void main(String args[]) throws Exception {
        final Thread thrdA = new Thread(() -> System.out.println("Message 1"));
        final Thread thrdB = new Thread(() -> System.out.println("Message 2"));
        final Thread thrdC = new Thread(() -> System.out.println("Message 3"));

        thrdA.start();
        thrdA.join();
        thrdB.start();
        thrdB.join();
        thrdC.start();
        thrdC.join();

    }
}

How would I implement this functionality using ExecutorServiceinstead of three thread objects?

我将如何使用ExecutorService而不是三个线程对象来实现此功能?

回答by Luiggi Mendoza

If what you want/need is to execute a group of jobs one after another but in a single thread different that the main app thread, then use Executors#newSingleThreadExecutor.

如果您想要/需要的是在与主应用程序线程不同的单个线程中一个接一个地执行一组作业,则使用Executors#newSingleThreadExecutor.

ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(() -> System.out.println("Message 1"));
es.submit(() -> System.out.println("Message 2"));
es.submit(() -> System.out.println("Message 3"));
es.shutdown();

回答by Amit Tamrakar

You can control sequential execution of threads using SingleThread ExecutorService with future.get() method.

您可以使用带有 future.get() 方法的 SingleThread ExecutorService 来控制线程的顺序执行。

DummyTask Class

DummyTask 类

import java.util.concurrent.Callable;

public class DummyTask implements Callable<Integer>
{

int taskId;

public DummyTask(int taskId) {
    this.taskId = taskId;
}

@Override
public Integer call() throws Exception
{
    System.out.println("excuting task... Task Id: " + taskId);
    return taskId;
}

}

SequentialExecution Class

顺序执行类

package com.amit.executorservice;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class SequentialExecution 
{
public static void main(String[] args) throws InterruptedException, ExecutionException {

    DummyTask task1 = new DummyTask(1);
    DummyTask task2 = new DummyTask(2);
    DummyTask task3 = new DummyTask(3);
    Future<Integer> result = null;
    ExecutorService executor = Executors.newSingleThreadExecutor();

    result = executor.submit( task1 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    result = executor.submit( task2 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    result = executor.submit( task3 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    executor.shutdown();

}
}

Output

输出

excuting task... Task Id: 1
excuting task... Task Id: 2
excuting task... Task Id: 3

Output will always be same and all task will get executed in sequence.

输出将始终相同,所有任务将按顺序执行。

回答by Alexei Kaigorodov

If you already use a thread pool in your application, you can reuse it by means of zero-threaded proxy serial executor, without creating special single threaded thread pool. One implementation is described in the javadoc section of Executor interface, another, optimized implementation, at my Github repository CodeSamples.

如果您的应用程序中已经使用了线程池,您可以通过零线程代理串行执行器来重用它,而无需创建特殊的单线程线程池。一个实现在Executor interfacejavadoc 部分进行了描述,另一个优化的实现在我的 Github 存储库CodeSamples 中