Scene: the control logic steps performed
Doug Lea's implementation CountDownLatch
Package com.dwz.concurrency2.chapter15; Import java.util.Random; Import java.util.concurrent.CountDownLatch; Import java.util.stream.IntStream; public class JDKCountDown { Private Final static the Random Random = new new the Random (System.currentTimeMillis ()); public static void main (String [] args) throws InterruptedException { Final CountDownLatch LATCH = new new CountDownLatch (5 ); System.out.println ( "ready multi-threaded processing tasks ..." ); // Step IntStream.rangeClosed (. 1,. 5) .forEach (I -> { new new the Thread (() -> { System.out.println (Thread.currentThread () getName (). + "Working IS." ); The try { the Thread. SLEEP (random.nextInt ( 1000 )); } the catch (InterruptedException E) { e.printStackTrace (); } // marking end latch.countDown (); }, String.valueOf (I)) Start ();. }) ; // wait for all tasks end latch.await (); //Step System.out.println ( "multi-threaded task all over, preparing for the second phase of the task" ); System.out.println ( "................... " ); System.out.println ( " FINISH " ); } }
A custom CountDown
package com.dwz.concurrency2.chapter15; public class CountDown { private final int total; private int counter = 0; public CountDown(int total) { this.total = total; } public void down() { synchronized (this) { this.counter++; this.notifyAll(); } } public void await() throws InterruptedException { synchronized (this) { while (counter != total) { this.wait(); } } } }
Custom CountDown test
Package com.dwz.concurrency2.chapter15; Import java.util.Random; Import java.util.concurrent.CountDownLatch; Import java.util.stream.IntStream; public class CustomCountDown { Private Final static the Random Random = new new the Random (System.currentTimeMillis ()); public static void main (String [] args) throws InterruptedException { Final CountDown LATCH = new new CountDown (5 ); System.out.println ( "ready multi-threaded processing tasks ..." ); // Step IntStream.rangeClosed (. 1,. 5) .forEach (I -> { new new the Thread (() -> { System.out.println (Thread.currentThread () getName (). + "Working IS." ); The try { the Thread. SLEEP (random.nextInt ( 1000 )); } the catch (InterruptedException E) { e.printStackTrace (); } // marking end latch.down (); }, String.valueOf (I)) Start ();. }) ; // wait for all tasks end latch.await (); // Step System.out.println ( "multi-threaded task all over, preparing for the second phase of the task" ); System.out.println ( "..................." ); System.out.println ( "FINISH" ); } }
Test Results:
Ready multi-threaded processing tasks. . .
Working IS 2.
4 IS Working.
1 IS Working.
3 IS Working.
5 IS Working.
Multithreaded all over, preparing for the second phase of the task
...................
FINISH