The synchronized keyword provided by Java provides thread-synchronous access to critical sections. Because it is difficult to synchronized based
The synchronization code is written correctly, and the Concurrency tool class provides an advanced Synchronizer. Countdown latch (countdown latch), Sync screen
(cyclic barrier), switch (exchanger), Semaphore (semaphore), and Phaser Synchronizer. The following main
Introduce the countdown latch.
The countdown latch causes one or more threads to wait at the "door" until another thread opens the door, and the thread
Before it can continue to run. He consists of a count variable and two operations, each of which "causes a thread to wait until
The count changes to 0 "and" Decrement count variable ".
Implementation class: Java.util.concurrent.CountDownLatch
The following code, implemented with a countdown latch, is the execution of all threads at the same time and ends before the main thread can proceed:
import java.util.concurrent.countdownlatch;import java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class test {final static int nthreads = 3;public static void main (String[] args) {final countdownlatch startsignal = new countdownlatch (1); final countdownlatch donesignal = new countdownlatch (nthreads); Runnable r = new runnable () {@Overridepublic void run () {try { System.out.println (Thread.CurrentThread (). GetName () + "Enter Wait"); startsignal.await (); System.out.println (Thread.CurrentThread (). GetName () + "Start performing tasks"); Thread.Sleep ($);d onesignal.countdown ();} catch (interruptedexception e) {e.printstacktrace ();}}; Executorservice es = executors.newfixedthreadpool (nthreads);for (int i = 0; i < nthreads; i++) {es.execute (r);} Try {thread.sleep (+); Startsignal.countdown (); System.out.println (Thread.CurrentThread (). GetName () + "Enter Wait");d onesignal.await (); System.out.println (Thread.CurrentThread (). GetName () + "Start Execution"); Es.shutdownnow ();} catch (interruptedexception e) {e.printstacktrace ();}}
Java Threading and concurrency programming Practice----synchronizer (countdown latch)