如何在执行器服务中按顺序执行任务?

2022-09-05 00:28:18

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

这是我的代码:

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


答案 1

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

答案 2

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

虚拟任务类

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

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


推荐