Java Concurrency Synchronization helper class Countdownlatch

Source: Internet
Author: User
Tags semaphore

Countdownlatch

Meaning:

Countdownlatch can be understood as a counter that sets the initial value when initializing, and calls the await () method when a thread needs to wait for certain operations to finish first. This method lets the thread go into hibernation until all the threads waiting are done. Each time the countdown () method is called, the internal counter is reduced by 1 until the counter wakes 0 o'clock. This can be understood as a special cyclicbarrier. Thread synchronization points are special, starting with an internal counter value of 0 o'clock.

Method:
Core Methods Two: Countdown () and await ()
Countdown (): To reduce the internal counters maintained by Countdownlatch by 1, each time the waiting thread completes the call
Await (): The thread puts this thread into hibernation when it executes to Countdownlatch

Example
Example of a meeting: Meeting in the Conference room before the meeting can begin.

import java.util.concurrent.CountDownLatch;public class VideoConference implements Runnable {private final CountDownLatch controller;public VideoConference(int number) {    controller = new CountDownLatch(number);}public void arrive(String name) {    System.out.printf("%s has arrived.\n", name);    controller.countDown();// 调用countDown()方法,使内部计数器减1    System.out.printf("VideoConference: Waiting for %d participants.\n", controller.getCount());}@Overridepublic void run() {    System.out.printf("VideoConference: Initialization: %d participants.\n", controller.getCount());    try {        controller.await();// 等待,直到CoutDownLatch计数器为0        System.out.printf("VideoConference: All the participants have come\n");        System.out.printf("VideoConference: Let‘s start...\n");    } catch (InterruptedException e) {        e.printStackTrace();    }}

}

Participation in Conference personnel category

Import Java.util.concurrent.semaphore;import Java.util.concurrent.timeunit;import Java.util.concurrent.locks.Lock Import Java.util.concurrent.locks.reentrantlock;public class PrintQueue {//semaphore private Semaphore semaphore;// Whether the free printer private Boolean freeprinters[];p rivate Lock lockprinters;public PrintQueue () {//Initialize three signals semaphore=new Semapho    Re (3);    Three free printers freeprinters=new boolean[3];    for (int i=0; i<3; i++) {freeprinters[i]=true; } lockprinters=new Reentrantlock ();}        public void PrintJob (Object document) {try {//Get semaphore semaphore.acquire ();        int Assignedprinter=getprinter ();        Long duration= (Long) (Math.random () *10); System.out.printf ("%s:printqueue:printing a Job in Printer%d during%d seconds\n", Thread.CurrentThread (). GetName (),        Assignedprinter,duration);        TimeUnit.SECONDS.sleep (duration);    Freeprinters[assignedprinter]=true;    } catch (Interruptedexception e) {e.printstacktrace ();      } finally {  Free the semaphore semaphore.release ();    }}private int GetPrinter () {int ret=-1;        try {lockprinters.lock ();                for (int i=0; i<freeprinters.length; i++) {if (Freeprinters[i]) {ret=i;                Freeprinters[i]=false;            Break    }}} catch (Exception e) {e.printstacktrace ();    } finally {Lockprinters.unlock (); } return ret;}

}

Test class:

public class CountDownLatchMain {public static void main(String[] args) {    VideoConference conference = new VideoConference(10);    Thread threadConference = new Thread(conference);    threadConference.start();// 开启await()方法,在内部计数器为0之前线程处于等待状态    for (int i = 0; i < 10; i++) {        Participant p = new Participant(conference, "Participant " + i);        Thread t = new Thread(p);        t.start();    }}

}

Massive video

Java Concurrency Synchronization helper class Countdownlatch

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.