Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...