Use of the "Java Concurrency" thread Sync tool cyclicbarrier

Source: Internet
Author: User
Tags semaphore

The previous section summarizes the use of the semaphore Synchronization tool, which semaphore mainly provides a count semaphore that allows the maximum number of threads to run. Cyclicbarrier is another synchronization tool that summarizes the use of Cyclicbarrier in this section. Let's take a look at the official introduction to Cyclicbarrier:

A synchronization helper class that allows a set of threads to wait for each other until a common barrier point (common barrier points) is reached. In programs that involve a set of fixed-size threads, these threads have to wait for each other, and cyclicbarrier is useful at this time. Because the barrier can be reused after releasing the waiting thread, it is called a cyclic barrier.

My explanation is this:

Cyclicbarrier can cause different threads to wait for each other, and then execute the following program after the different threads have finished executing. For example, A, B, c three students to play, the bus at the school gate, A, B, c respectively from their own bedroom out, have arrived at the bus, the first must wait, until three students have come, the bus to go. They want to play two places M and N, to the M, three students went to play, after the end of their respective back to the bus, the first to come back must wait until three students have arrived, the bus to N place, the bus can be recycled. This bus is cyclicbarrier.

The Cyclicbarrier synchronization tool is relatively straightforward, because the functionality is clear and a cyclicbarrier example code is written below:

 Public  class cyclicbarriertest {     Public Static void Main(string[] args) {Executorservice service = Executors.newcachedthreadpool ();FinalCyclicbarrier cb =NewCyclicbarrier (3);//Set to three threads to wait, all executed and then downSystem.out.println ("Initialize: currently available"+ (cb.getnumberwaiting () +"A thread is waiting"));//3 quests         for(inti =0; I <3; i++) {Runnable run =NewRunnable () { Public void Run() {Try{Thread.Sleep (Long) (Math.random () *10000)); System.out.println (Thread.CurrentThread (). GetName () +"Approaching meeting point 1, currently available"+ (cb.getnumberwaiting () +1) +"A thread arrives,"+ (cb.getnumberwaiting () = =2?"All are up, go to Rendezvous point 2!" ":"Waiting ..."));//After access, release, if the following statement is masked, only 3 records can be printed in the console and the thread is blockedCb.await ();//WaitThread.Sleep ((Long) (Math.random () *10000)); System.out.println (Thread.CurrentThread (). GetName () +"Approaching meeting point 2, currently available"+ (cb.getnumberwaiting () +1) +"A thread arrives,"+ (cb.getnumberwaiting () = =2?"All are up, go to Rendezvous point 3!" ":"Waiting ..."));                        Cb.await (); Thread.Sleep ((Long) (Math.random () *10000)); System.out.println (Thread.CurrentThread (). GetName () +"Approaching meeting point 3, currently available"+ (cb.getnumberwaiting () +1) +"A thread arrives,"+ (cb.getnumberwaiting () = =2?"It's all here, it's done!" ":"Waiting ..."));                    Cb.await (); }Catch(Exception e)              {                      }                  }              }; Service.execute (run);//Perform Tasks} service.shutdown ();//Close thread}}

As can be seen from the code, the use of Cyclicbarrier mainly has two points, one is initialization, the other is to call the await () method. This await () method is the "public barrier point" in the official explanation, at which point all the threads have to wait until the specified number of threads is fully reachable to proceed. Look at the effect of the operation:

Initialize: There are currently 0 threads waiting
Pool-1-thread-3 is about to arrive at meeting point 1, there are currently 1 threads arriving, waiting ...
Pool-1-thread-2 is about to arrive at meeting point 1, there are currently 2 threads arriving, waiting ...
Pool-1-thread-1 is about to arrive at the meeting point 1, there are currently 3 threads arrived, all to the point, go to Rendezvous 2!
Pool-1-thread-2 is about to arrive at meeting point 2, there are currently 1 threads arriving, waiting ...
Pool-1-thread-3 is about to arrive at meeting point 2, there are currently 2 threads arriving, waiting ...
Pool-1-thread-1 is about to arrive at the meeting point 2, there are currently 3 threads arrived, all to the point, go to Rendezvous 3!
Pool-1-thread-3 is about to arrive at meeting point 3, there are currently 1 threads arriving, waiting ...
Pool-1-thread-1 is about to arrive at meeting point 3, there are currently 2 threads arriving, waiting ...
Pool-1-thread-2 is about to arrive at the meeting point 3, there are currently 3 threads arrived, all to the same, the execution is complete!

Cyclicbarrier's application is also obvious: in a certain demand, such as a large task, often need to allocate a lot of sub-tasks to execute, only when all the subtasks are completed to perform the main task, this time, you can choose Cyclicbarrier.
It can be a bit more precise: if we need to count the business data of the whole country, the databases of the provinces are independent, that is to say, by the provincial sub-Library. and statistics of the amount of data is very large, the statistical process is relatively slow. To improve performance, calculate quickly. We take a concurrent approach, multiple threads simultaneously calculate the data of each province, and then summarize the statistics, where cyclicbarrier is very useful.
The Cyclicbarrier Sync tool summarizes so much!
  

Related reading: http://blog.csdn.net/column/details/bingfa.html

-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15

Use of the "Java Concurrency" thread Sync tool 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.