Java Multithreading--the use of synchronization barrier Cyclicbarrier

Source: Internet
Author: User

Cyclicbarrier's concept understanding:

Cyclicbarrier literally means a recyclable barrier, which is a synchronization tool class in Java and contracted Java.util.concurrent , which is explained in the Chinese document of the JDK1.6 I downloaded:

The general meaning is: to have a group of threads reach a barrier, a collection point is blocked, until all the threads arrive at this set point, the barrier will open, and then the thread can continue to execute. A simple example is: Tour groups with a group of people to visit the attractions, set at the next spot in a place, So the guide is in the sights a waiting for everyone, the guide is this meeting point or barrier, until all the visitors gathered, the guide will take everyone to continue to visit the next attraction B.

use of Cyclicbarrier:

Cyclicbarrier has two constructors:

Cyclicbarrier (int parties); The parameters of type int indicate that there are several threads involved in this barrier interception, (take the example above, that is, several people travel with the group);

Cyclicbarrier (int parties,runnable barrieraction), barrieraction this thread is prioritized when all threads reach a barrier point.

One of the most important methods:

await (); Each thread calls await (), indicating that I have reached the barrier point, and then the current thread is blocked, (take the example above that the visitor A is arriving at attraction a, and he is there waiting for everyone to get there).

Application Scenarios:

Cyclicbarrier can be used for multi-threaded computing data, finally merging the results of the scene, I did not use this class, all can simply simulate a function.

Requirements Description:

Suppose you now need to calculate the average score of 3 students,
Each student has a total of three achievements.
The steps are: Calculate the average score for each student first
The average score of three students is calculated according to the average score of each student.
Using Cyclicbarrier

 PackageCom.wang.thread1;ImportJava.util.Set;Importjava.util.concurrent.BrokenBarrierException;ImportJava.util.concurrent.ConcurrentHashMap;ImportJava.util.concurrent.CyclicBarrier;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Assuming that you now need to calculate the average score of 3 students, * each student has a total of three results * steps are: First calculate the average score per student * and then calculate the average score of each student according to their average score * use Cyclicbarrier *@authorAdministrator **/ Public classCyclicBarrier1Implementsrunnable{//creating a thread pool that initializes 3 threads    PrivateExecutorservice Threadpool=executors.newfixedthreadpool (3); //Create 3 Cyclicbarrier objects and execute the Run method of the current class after execution    PrivateCyclicbarrier cb=NewCyclicbarrier (3, This); //save each student's average score    PrivateConcurrenthashmap<string, integer> map=NewConcurrenthashmap<string,integer>();  Public voidcount () { for(inti=0;i<3;i++) {Threadpool.execute (NewRunnable () {@Override Public voidrun () {//calculates the average score for each student, the code is slightly () assumed to be a random number of 60~100                    intScore= (int) (Math.random () *40+60);                    Map.put (Thread.CurrentThread (). GetName (), score); System.out.println (Thread.CurrentThread (). GetName ()+ "Average student's score is" +score); Try {                        //run await (), waiting for all students to finish the average scorecb.await (); } Catch(Interruptedexception |brokenbarrierexception e)                    {E.printstacktrace ();        }                }                            }); }} @Override Public voidrun () {intResult=0; Set<String> set =Map.keyset ();  for(String s:set) {result+=Map.get (s); } System.out.println ("Average score for three people:" + (RESULT/3) + "min"); }     Public Static voidMain (string[] args) {CyclicBarrier1 CB=NewCyclicBarrier1 ();    Cb.count (); }}

The printing results are as follows:

Java Multithreading--the use of synchronization 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.