Wait until child threads completed : Java

前端 未结 6 748
被撕碎了的回忆
被撕碎了的回忆 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:43

    There are many ways to approach this. Consider CountDownLatch:

    import java.util.concurrent.CountDownLatch;
    
    public class WorkerTest {
        final int NUM_JOBS = 3;
        final CountDownLatch countDownLatch = new CountDownLatch(NUM_JOBS);
        final Object mutex = new Object(); 
        int workData = 0;
    
        public static void main(String[] args) throws Exception {
            WorkerTest workerTest = new WorkerTest();
            workerTest.go();
            workerTest.awaitAndReportData();
        }
    
        private void go() {
            for (int i = 0; i < NUM_JOBS; i++) {
                final int fI = i;
                Thread t = new Thread() {
                    public void run() {
                        synchronized(mutex) {
                            workData++;
                        }
                        try {
                            Thread.sleep(fI * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        countDownLatch.countDown();
                    }
                };
                t.start();
            }
        }
    
        private void awaitAndReportData() throws InterruptedException {
            countDownLatch.await();
            synchronized(mutex) {
                System.out.println("All workers done. workData=" + workData);
            }
        }
    }
    

提交回复
热议问题