Wait until child threads completed : Java

前端 未结 6 755
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 04:08

Problem description : -

Step 1: Take input FILE_NAME from user at main thread.

Step 2: Perform 10 operations on

6条回答
  •  半阙折子戏
    2020-11-30 04:58

    You may want to choose CountDownLatch from java.util.concurrent. From JavaDocs:

    A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

    Sample code:

    import java.util.concurrent.CountDownLatch;
    
    public class Test {
        private final ChildThread[] children;
        private final CountDownLatch latch;
    
        public Test() {
            this.children = new ChildThread[4];
            this.latch = new CountDownLatch(children.length);
            children[0] = new ChildThread(latch, "Task 1");
            children[1] = new ChildThread(latch, "Task 2");
            children[2] = new ChildThread(latch, "Task 3");
            children[3] = new ChildThread(latch, "Task 4");
        }
    
        public void run() {
            startChildThreads();
            waitForChildThreadsToComplete();
        }
    
        private void startChildThreads() {
            Thread[] threads = new Thread[children.length];
    
            for (int i = 0; i < threads.length; i++) {
                ChildThread child = children[i];
                threads[i] = new Thread(child);
                threads[i].start();
            }
        }
    
        private void waitForChildThreadsToComplete() {
            try {
                latch.await();
                System.out.println("All child threads have completed.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        private class ChildThread implements Runnable {
            private final String name;
            private final CountDownLatch latch;
    
            protected ChildThread(CountDownLatch latch, String name) {
                this.latch = latch;
                this.name = name;
            }
    
            @Override
            public void run() {
                try {
                    // Implementation
                    System.out.println(name + " has completed.");
                } finally {
                    latch.countDown();
                }
            }
        }
    
        public static void main(String[] args) {
            Test test = new Test();
            test.run();
        }
    }
    

    Output:

    Task 1 has completed. Task 4 has completed. Task 3 has completed. Task 2 has completed. All child threads have completed.

提交回复
热议问题