Java concurrent Programming principle and Combat 26: Latching Countdownlatch

Source: Internet
Author: User
Tags visibility volatile

About the lock Countdownlatch before I saw an example of a very image on the internet, but do not remember where it came from, so here is to write a re-article it:

Examples are as follows:

We qizaotanhei every day to work, parents have to work every day, a day to set up a restaurant, family together to eat a meal, notify everyone to go to the restaurant collection.

Assume: 3 people work in different places, must wait until 3 people to the scene in order to eat, with the program how to achieve it?

Way One:

 Public classtest1{/*** Simulate dad going to the hotel*/     Public Static voidfathertores () {System.out.println ("It takes 3 hours for dad to walk to the hotel. "); }     /*** mock me to the hotel*/     Public Static voidmothertores () {System.out.println ("It takes 2 hours for mom to get to the hotel by bus. "); }     /*** Simulated mother to the hotel*/     Public Static voidmetores () {System.out.println ("I need 1 hours to get to the hotel by subway. "); }     /*** The Mock family is here.*/     Public Static voidtogethertoeat () {System.out.println ("The family arrived, and began to eat."); }      Public Static voidMain (string[] args) {fathertores ();        Mothertores ();        Metores ();    Togethertoeat (); }}

Output Result:

It takes 3 hours for dad to walk to the hotel. It takes 2 hours for mom to squeeze the bus to the hotel. It takes me 1 hours to get to the hotel by subway. The whole family is here, start eating.

Seemingly realized, but eat a meal, the light convergence spent 6 hours, the first to wait for 3 hours, and then back to the hotel, we gathered at the same time, how is also a parallel process, so do not I say, everyone must think of using multi-threading, so as a senior cock Silk program Ape, began to transform our code:

Way two:

 Public Static voidMain (string[] args) {NewThread () { Public voidrun () {fathertores ();        };        }.start (); NewThread () { Public voidrun () {mothertores ();        };        }.start (); NewThread () { Public voidrun () {metores ();        };                }.start ();    Togethertoeat (); }

3 threads were started directly, but the results did not seem to be working:

The family arrived, began to eat I take the subway to the hotel takes 1 hours. It takes 2 hours for mom to squeeze the bus to the hotel. It takes 3 hours for dad to walk to the hotel.

One didn't arrive, and began to eat,,, (for better display, I rested in each method for a period of time, simulating the process of arriving at the hotel). Or not, then continue to improve:

Way three:

Private Static volatile inti = 3;  Public Static voidMain (string[] args) {NewThread () { Public voidrun () {fathertores (); I--;        };        }.start (); NewThread () { Public voidrun () {mothertores (); I--;        };        }.start (); NewThread () { Public voidrun () {metores (); I--;        };         }.start ();  while(I! = 0);    Togethertoeat (); }

We have defined a volatile modified int type variable with an initial value of 3, when 0 o'clock represents a family, so we used a busy in the main thread, waiting for everyone to arrive, this effect looks good oh:

It takes me 1 hours to get to the hotel by subway. It takes 2 hours for mom to squeeze the bus to the hotel. It takes 3 hours for dad to walk to the hotel. The whole family is here, start eating.

However, busy waiting for such a code is too expensive for the CPU, and we need a better way to implement it. By the way, volatile, why do we use the volatile modifier I, because when multiple threads manipulate the same variable, in order to ensure that variable modification for other threads of visibility, must use synchronization, volatile for the implementation of the visibility is a good choice, but our code in the I-- It is also possible because of concurrency caused certain problems, after all, i--is not atomic operation, it is best to use synchronous block or atomiclong.decrementandget () to achieve--。

Said so much, the title of the Countlatchdown unexpectedly did not appear, so the final version, must let this buddy out debut:

Mode four:

Private StaticCountdownlatch latch =NewCountdownlatch (3);  Public Static voidMain (string[] args)throwsinterruptedexception {NewThread () { Public voidrun () {fathertores ();            Latch.countdown ();        };        }.start (); NewThread () { Public voidrun () {mothertores ();            Latch.countdown ();        };        }.start (); NewThread () { Public voidrun () {metores ();            Latch.countdown ();        };         }.start ();        Latch.await ();    Togethertoeat (); }

Output Result:

It takes me 1 hours to get to the hotel by subway. It takes 2 hours for mom to squeeze the bus to the hotel. It takes 3 hours for dad to walk to the hotel. The whole family is here, start eating.

Avoid the use of busy, etc., we use the countdowmlatch to achieve our needs. Here's a detailed description of this buddy:

The meaning of latch latching is a kind of synchronous tool class. Similar to a door: Before the latch reaches the end state, the door is closed, no threads are allowed to pass, and when the end state is reached, the door opens and allows all threads to pass. And when the door is open, it stays open forever.

Role: can be used to ensure that certain activities are not resumed until other activities have been completed.

Usage scenarios:

1, for example, in our example, everyone arrives at the restaurant and eats;

2. Initialization of resources required for an operation is complete

3, a service depends on the thread all open and so on ...

Countdowmlatch is a flexible latching implementation that contains a counter that is initialized to a positive number, which indicates how many events need to wait. The countdown method decrements the counter, indicating that an event occurred, while the await method waits for the counter to reach 0, indicating that all the waiting things have been done.

Java concurrent Programming principle and Combat 26: Latching Countdownlatch

Related Article

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.