Java Concurrency Tool Class (ii) synchronization barrier Cyclicbarrier

Source: Internet
Author: User

Role

Cyclicbarrier is a synchronous helper class that allows a group of threads to wait on each other until it reaches a common barrier point (common barrier points) to continue execution.

Brief introduction

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), whose parameters represent the number of threads that the barrier intercepts, and each thread calls the await method to tell Cyclicbarrier I have reached the barrier, and then the current thread is blocked.

Application Scenarios

Cyclicbarrier can be used for multithreaded computing data, and finally the application scenario of combining the results. For example, we use an Excel to save the user all bank water, each sheet to save an account for nearly a year of each bank of water, now need to count the user's Daily bank water, the first multi-threaded processing each sheet in the bank of water, after the execution, get each sheet daily bank water, Finally, we use barrieraction to calculate the average daily bank flow of the whole Excel using the calculation results of these threads.

code example

The instance code is as follows:

1  Public classCyclicbarriertest {2 3     StaticCyclicbarrier C =NewCyclicbarrier (2);4 5      Public Static voidMain (string[] args) {6         NewThread (NewRunnable () {7 8 @Override9              Public voidrun () {Ten                 Try { One c.await (); A}Catch(Exception e) { -  -                 } theSYSTEM.OUT.PRINTLN (1); -             } - }). Start (); -  +         Try { - c.await (); +}Catch(Exception e) { A  at         } -SYSTEM.OUT.PRINTLN (2); -     } -}

Output

21st

or output

12

  

If the new Cyclicbarrier (2) is modified to new Cyclicbarrier (3) then the main thread and the child thread will wait forever because no third thread is executing the await method, that is, no third thread has reached the barrier, so two threads that have previously reached the barrier will not continue to execute.

Cyclicbarrier also provides a higher-level constructor Cyclicbarrier (int parties, Runnable barrieraction), which performs barrieraction when the thread arrives at the barrier, Facilitates handling of more complex business scenarios. Barrieraction After the number of Cyclicbarrier is reached, all other threads are executed before being awakened.

The code is as follows:

1  Public classCyclicBarrierTest2 {2 3     StaticCyclicbarrier C =NewCyclicbarrier (2,NewA ());4 5      Public Static voidMain (string[] args) {6         NewThread (NewRunnable () {7 8 @Override9              Public voidrun () {Ten                 Try { One c.await (); A}Catch(Exception e) { -  -                 } theSYSTEM.OUT.PRINTLN (1); -             } - }). Start (); -  +         Try { - c.await (); +}Catch(Exception e) { A  at         } -SYSTEM.OUT.PRINTLN (2); -     } -  -     Static classAImplementsRunnable { -  in @Override -          Public voidrun () { toSYSTEM.OUT.PRINTLN (3); +         } -  the     } *  $}

Output

312

  

The difference between Cyclicbarrier and Countdownlatch
    • 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.
    • 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.

The use code for IsBroken is as follows:

1 Importjava.util.concurrent.BrokenBarrierException;2 ImportJava.util.concurrent.CyclicBarrier;3 4  Public classCyclicBarrierTest3 {5 6     StaticCyclicbarrier C =NewCyclicbarrier (2);7 8      Public Static voidMain (string[] args)throwsinterruptedexception, brokenbarrierexception {9Thread thread =NewThread (NewRunnable () {Ten  One @Override A              Public voidrun () { -                 Try { - c.await (); the}Catch(Exception e) { -                 } -             } -         }); + Thread.Start (); - Thread.Interrupt (); +         Try { A c.await (); at}Catch(Exception e) { - System.out.println (C.isbroken ()); -         } -     } -}

Output

True

Reference: The Art of Java concurrent programming

  

Java Concurrency Tool Class (ii) synchronization barrier Cyclicbarrier

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.