简体   繁体   中英

How to execute tasks in ExecutorService sequentially?

I have three threads that are joined, ie 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 ExecutorService instead of three thread objects?

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 .

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

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

DummyTask Class

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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