Java multithreading-two commonly used thread counters Countdownlatch and loop barrier Cyclicbarrier

Source: Internet
Author: User

Java multithreaded Programming-(1)-Thread safety and lock synchronized concepts

Java multithreaded Programming-(2)-reentrant locks and other basic features of synchronized

Java multithreaded Programming-(3)-Talk about the volatile keyword from a wrong double-check lock code

Java multithreaded Programming-(4)-Introduction and use of thread-local threadlocal

Java multithreaded Programming-(5)-Introduction and use of inter-thread communication mechanism

Java multithreaded Programming-(6)-Are you still using wait/notify for interprocess communication? Java multithreaded Programming-(7)-use Reentrantreadwritelock to implement lock concurrency one, Countdown countdownlatch

Countdownlatch is a very useful multi-line program-control tool class called a "Countdown timer," which allows one or more threads to wait until the operation of another thread has finished executing.

Give examples:

We know that the collection of seven Dragon beads can summon the dragon, then we call together, below I need to send 7 people (7 threads) to find the 7 different dragon beads, each found after the return to tell me also need to wait for the number of dragon beads minus 1, then when all the people have found the Dragon Ball, Then I can summon the dragon.

By the way, write a code like this:

The results of the operation are as follows:

The above results can be seen when the allocation of 7 people (7 threads) after the Dragon bead is found, that is, all the threads executed before the Dragon Ball can summon (execute countdownlatch.await () after the code).

Attention:

(1) Countdownlatch constructor

7 indicates the number of threads that need to wait for execution to complete.

(2) After each thread executes, the method needs to be executed countDownLatch.countDown() , otherwise the counter will not be accurate;

(3) After all threads have been executed, the following code will be executed countDownLatch.await() ;

(4) can be seen in the above code Countdownlatch blocking is the main thread;

Well, if we're not using the counter countdownlatch, the results are conceivable, as shown here:

The result can only hehe!

All right! Above said a bunch of water words, below say some official explanation:

Countdownlatch is introduced in java1.5, it exists under the Java.util.concurrent package. Countdownlatch This class enables a thread to wait for other threads to complete their work before executing. For example, the main thread of the application wants to execute after all the framework services have been started by the threads that are responsible for starting the framework service.

The Countdownlatch is implemented by a counter, where the initial value of the counter is the number of threads. Each time a thread finishes its task, the value of the counter is reduced by 1. When the counter value reaches 0 o'clock, it means that all the threads have completed the task, and then the thread waiting on the latch can resume the execution of the task.

constructors defined in the Countdownlatch.java class:

The count value in the constructor is actually the number of threads that the latch needs to wait. This value can only be set once, and Countdownlatch does not provide any mechanism to reset the count value.

The first interaction with Countdownlatch is the main thread waiting for other threads. The main thread must call the Countdownlatch.await () method immediately after starting another thread. This way the main thread will block on this method until other threads have completed their respective tasks.

Other n threads must refer to the latching object because they need to notify the Countdownlatch object that they have completed their respective tasks. This notification mechanism is done through the Countdownlatch.countdown () method, and each time this method is called, the count value initialized in the constructor is reduced by 1. So when n threads call this method, the value of Count equals 0, and the main thread can resume its own task by using the await () method.

Second, Countdownlatch in the real-time system of the use of the scene

Let's try to list the usage scenarios for Countdownlatch in a Java real-time system. What I have listed is all I can think of. If you have any other possible ways to use it, please list it in your message and it will help you.

(1) Achieve maximum parallelism: Sometimes we want to start multiple threads at the same time, to achieve the greatest degree of parallelism. For example, we want to test a singleton class. If we create a countdownlatch with an initial count of 1 and have all the threads waiting in this lock, we can easily complete the test. We just call the countdown () method once to get all the waiting threads to resume execution at the same time.

(2) Wait for n threads to complete their tasks before starting execution: for example, an application startup class to ensure that all n external systems are up and running before processing user requests.

(3) Deadlock detection: A very handy scenario is that you can use n threads to access a shared resource, the number of threads in each test phase is different, and an attempt to generate a deadlock.

Third, the circulation barrier Cyclicbarrier

Cyclicbarrier is another multi-threaded concurrency control tool, and Countdownlatch is very similar, he can also implement the count between threads wait, but his function is more powerful than Countdownlatch.

Cyclicbarrier literally means a barrier (Barrier) that can be recycled (Cyclic). What it does is to block a group of threads from reaching a barrier (also called a sync point), until the last thread reaches the barrier, the barrier opens, and all the threads that are blocked by the barrier continue to work.

Cyclicbarrier the default constructor is CyclicBarrier(int parties) that its parameters represent the number of threads that the barrier intercepts, and each thread calls the await method that tells Cyclicbarrier I have reached the barrier, and then the current thread is blocked.

Cyclicbarrier stressed that n threads, everyone waits, as long as one is not finished, everyone has to wait.

And then the above "set up seven dragon beads!" The story of summoning the dragon. Summon the dragon, need 7 mage to look for dragon bead, but these 7 mage not suddenly can call up, so to wait to call up 7 mage, and then in the autumn peak Buddhist incense for these 7 mage off, let them go at the same time, go to different places looking for Dragon Ball (knocking Blackboard: This is the first barrier point), After the seven mages had agreed to find the Dragon Ball, they returned to this place and waited for the other mages to find the Dragon Ball and see me together. A few years later, the first mage came back and waited for the other mages ... , and all the Mages in the end (knocking the blackboard: This is the first barrier point), then team up to find me summon the dragon.

The sample code is as follows:

Execution Result:

The code is set up two barrier points, the first for the convening of 7 mages, and so on 7 wizards gathered, set at a barrier point, 7 mage to find the Dragon Ball, and then summon the dragon, the middle has a nested relationship!

The above example, roughly speaking of a barrier, is set up with two barriers, and does not demonstrate the reusable (Cyclic) barrier (Barrier) in the above mentioned recyclable (Cyclic)

Looking CyclicBarrier.reset() at this, you can get Cyclicbarrier back to its initial state, which is no longer demonstrated due to the relatively small number of uses.

Iv. the difference between Cyclicbarrier and Countdownlatch

(1) The Countdownlatch counter can only be used once. The Cyclicbarrier counter can be reset using the Reset () method. So cyclicbarrier can handle more complex business scenarios, such as resetting the counters and having the threads perform them again if the calculations are wrong.

(2) Cyclicbarrier also provides other useful methods, such as the Getnumberwaiting method, to get the number of threads Cyclicbarrier blocked. The IsBroken method is used to know if the blocked thread is interrupted. The following code, for example, returns True when it finishes executing.

(3) Countdownlatch blocks the main thread, Cyclicbarrier does not block the main thread and only blocks child threads.

Java multithreading-two commonly used thread counters Countdownlatch and loop barrier Cyclicbarrier

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.