javamultithreadingconcurrency

How to execute tasks in ExecutorService sequentially?


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 ExecutorService instead of three thread objects?


Solution

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