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

时间:2015-08-16 17:14:55

标签: java multithreading concurrency

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

这是我的代码:

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();

    }
}

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

3 个答案:

答案 0 :(得分:21)

如果您想要/需要的是一个接一个地执行一组作业,但是在与主应用程序线程不同的单个线程中,则使用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();

答案 1 :(得分:4)

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

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();

}
}

<强>输出

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

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

答案 2 :(得分:1)

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