Getting started with CountDownLatch thread synchronization in java

Source: Internet
Author: User

Getting started with CountDownLatch thread synchronization in java

A synchronization helper class that allows one or more threads to wait until a group of operations are performed in another thread.

Two inverted-count latches are used below: one is waiting for the other to complete.

Import java. util. concurrent. countDownLatch; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class CountDownLatchTest {/*** @ param args */public static void main (String [] args) {ExecutorService ThreadPool = Executors. newCachedThreadPool (); final CountDownLatch cdOrder = new CountDownLatch (1); final CountDownLatch cdAnswer = new CountDownLatch (3); for (int I = 0; I <3; I ++) {Runnable runnable = new Runnable () {@ Override public void run () {try {System. out. println ("Thread" + Thread. currentThread (). getName () + "waiting to receive command"); cdOrder. await (); System. out. println ("Thread" + Thread. currentThread (). getName () + "commands accepted"); Thread. sleep (long) Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "response command, processing result"); cdAnswer. countDown ();} catch (InterruptedException e) {e. printStackTrace () ;}}; ThreadPool.exe cute (runnable);} try {Thread. sleep (long) Math. random () * 10000); System. out. println ("Thread" + Thread. currentThread (). getName () + "waiting for command release"); cdOrder. countDown (); cdAnswer. await (); System. out. println ("Thread" + Thread. currentThread (). getName () + "command released, waiting for result"); System. out. println ("All commands have been processed");} catch (InterruptedException e) {e. printStackTrace ();} ThreadPool. shutdown ();}}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.