Java Concurrency Synchronization helper class Cyclicbarrier

Source: Internet
Author: User

Cyclicbarrier Meaning:

Fences allow two or more threads to synchronize at a collection point. When a thread arrives at the collection point, it calls the await () method to wait for the other thread. After the thread invokes the await () method, Cyclicbarrier blocks the thread and put it into hibernation waiting for other threads to arrive. When the last thread calls the await () method, Cyclicbarrier will wake up all the waiting threads and then those threads will continue to execute. Cyclicbarrier can pass in another Runnable object as an initialization parameter. When all the threads have reached the collection point, the Cyclicbarrier class executes the Runnable object as a thread.

Method:
Await (): Causes the thread to hibernate until the last thread arrives and wakes all dormant threads

Example
Finds a specified number in a matrix (a two-dimensional array). The matrix is divided into subsets, with each subset assigned to a thread to find. When all threads have been found, the final thread is given a summary of the results.
Find class: Finds the specified number in a subset, finds and then stores the result after the call to await () method is placed into hibernation waiting for the last thread to wake up

Import Java.util.list;import Java.util.concurrent.brokenbarrierexception;import  Java.util.concurrent.cyclicbarrier;public class Searcher implements Runnable {private Cyclicbarrier barrier;private Int[] submock;private list<result> result;private int row;private int searchnmu;public Searcher (int[] Submock, Lis    T<result> Result, cyclicbarrier barrier, int row, int searchnmu) {this.barrier = barrier;    This.submock = Submock;    This.result = result;    This.row = row; This.searchnmu = Searchnmu;} @Overridepublic void Run () {System.out.printf ("%s:processing lines from%d. \ n", Thread.CurrentThread (). GetName (), RO    W);            for (int i=0; i<submock.length; i++) {if (submock[i] = = SEARCHNMU) {result r = new result ();            R.setrow (row);            R.setcol (i);        Result.add (R);    }} System.out.printf ("%s:lines processed.\n", Thread.CurrentThread (). GetName ());    try {barrier.await (); } catch (Interruptedexception e) {e.printstacktrace ();    } catch (Brokenbarrierexception e) {e.printstacktrace (); }}}

Result class:

public class Result {//行int row;//列int col;public int getRow() {    return row;}public void setRow(int row) {    this.row = row;}public int getCol() {    return col;}public void setCol(int col) {    this.col = col;}

}

Summary class: Summarizes the results found for each searcher:
Import java.util.List;

public class Grouper implements Runnable {

private List<Result> result;int[][] mock;public Grouper(List<Result> result, int[][] mock) {    this.result = result;    this.mock = mock;}@Overridepublic void run() {    System.out.printf("Grouper: Processing results...\n");    for (int i = 0; i < result.size(); i++) {        Result r = result.get(i);        if(r!=null)        System.out.println("mock[" + r.row + "][" + r.col + "]" + mock[r.row][r.col]);    }    System.out.printf("Grouper proccessing end...\n");}}

The main function, how to searcher and Grouper class together??

Import Java.util.arraylist;import Java.util.list;import Java.util.concurrent.cyclicbarrier;public class    Cyclicbarriermain {public static void main (string[] args) {//data to find final int SEARCH = 5;  Matrix Declaration int[][] mock = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 2, 3, 5, 5, 6, 7, 8, 9, 10}, { 5, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 2, 3, 4, 6, 6, 7, 8, 5, 10}, {1, 5, 3, 4, 5, 6, 7, 8, 5,    10}, {1, 5, 3, 4, 12, 6, 7, 8, 0, 5}};    Number of threads found int participants = Mock.length;    list<result> Result = new arraylist<result> ();    Rollup Thread Grouper grouper = new Grouper (result, mock);    Fence, incoming parameter meaning: number of thread synchronizations, rollup thread cyclicbarrier barrier = new Cyclicbarrier (participants, Grouper);    Searcher searchers[] = new Searcher[participants];        for (int i = 0; i < participants; i++) {searchers[i] = new Searcher (mock[i], result, barrier, I, SEARCH);      Thread thread = new Thread (Searchers[i]);  Thread.Start (); } System.out.printf ("Main:the Main thread has finished.\n");}

}

Places to be aware of
After the thread finishes the task, call the await () method of Cyclicbarrier to hibernate the wait. When all threads arrive at the rendezvous point, the fence invokes the incoming Runnable object for final execution.
The difference from Countdownlatch:
Accepts an object of type runnable as subsequent execution after all threads have reached the meeting point
The Call Countdown () method is not displayed
Countdownlatch generally can only be used once, cyclicbarrier can be used multiple times
Application Scenarios
Multiple threads do the task, wait until the meeting point is synchronized and give the following thread a summary

Various IT video capture

Java Concurrency Synchronization helper class 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.