The use of the Java multi-thread ~~~cyclicbarrier class

Source: Internet
Author: User

The previous section describes how countdown is used, and Java provides a more advanced way to synchronize the collaboration between multiple threads to actually

Now, this class is cyclicbarrier. It can be implemented when multiple sub-branches complete their work, call the await method to wait, and then wait for all the points

After the route is finished, the main thread's Run method is automatically called, and the main thread is a class that implements the Runnable interface, which is instantiated in Cyclicbarrier

When it is called.

Let's use the code to illustrate the problem. The effect of the code implementation is to query from a two-dimensional array to the number we need, and then branch into five

Threads are calculated from different starting points, and then finally called Grouper threads to merge the results of the calculation to get the final result.


Package Com.bird.concursey.charpet4;import java.util.random;/** * This class would generate a Random matrix of Numbersbetwe En one and where the threads is going to look for a number. * @author Bird * September 22, 2014 morning 9:43:49 */public class Matrixmock {private int data[][];/** * Fill The matrix with random Nu Mbers. Each time you generate a number, compare Itwith the number is going to look for. If They is equal, increment the counter. * @param size * @param length * @param number */public matrixmock (int size, int length, int number) {int counter = 0;data = new Int[size][length]; Random random = new random (), for (int i = 0, i < size; i++) {for (int j = 0; J < length; J + +) {Data[i][j] = Random.nex TInt, if (data[i][j] = = number) {counter++;}}} System.out.printf ("Mock:there is%d ocurrences of number in generated data.\n", Counter,number);} /** * This method receives an int parameter with thenumber of a row in the matrix and returns the row if it exists, and re Turns null if ITDOESN' t exist. * @param row * @return */public int[] GetRow (int row) {if (Row > 0 && row > Data.length) {return data[row];} return null;}}



Package com.bird.concursey.charpet4;/** * Results. This class would store, in a array, thenumber of occurrences of the searched number in each row of the matrix. * @author Bird * September 22, 2014 morning 9:52:05 */public class Results {private int[] data;public Results (int size) {data = new int[ Size];}  /** * This method receives a position in the array anda value as parameters, and establishes the value of the. Position in The array. * @param position * @param value */public void setData (int position, int value) {Data[position] = value;} Public int[] GetData () {return data;}}


Package Com.bird.concursey.charpet4;import Java.util.concurrent.brokenbarrierexception;import Java.util.concurrent.cyclicbarrier;public class Searcher implements Runnable {private int firstrow;private int lastrow; Private Matrixmock mock;private Results results;private int number;private cyclicbarrier cyclibarrier;public Searcher ( int firstrow, int lastrow, matrixmock mock,results Results, int number, Cyclicbarrier cyclibarrier) {super (); This.firstro w = Firstrow;this.lastrow = Lastrow;this.mock = Mock;this.results = Results;this.number = Number;this.cyclibarrier = Cycli Barrier;} @Overridepublic void Run () {int counter; System.out.printf ("%s:processing lines from%d to%d.\n", Thread.CurrentThread (). GetName (), firstrow,lastrow); for (int i = FirstRow; i < lastrow; i++) {int row[] = Mock.getrow (i); counter = 0;for (int j = 0; J < Row.length; J + +) {if (row[j] = = number) {counter++;}} Results.setdata (i, counter);} System.out.printf ("%s:lines processed.\n", Thread.CurrentThread (). GetName ()); try {Cyclibarrier.await ();} catch (Interruptedexception e) {e.printstacktrace ();} catch (Brokenbarrierexception e) {e.printstacktrace ()}}}

Package Com.bird.concursey.charpet4;import Java.util.concurrent.cyclicbarrier;public class Grouper implements Runnable {private Results results;public grouper (Results Results) {super (); this.results = Results;} @Overridepublic void Run () {int finalresult = 0; System.out.printf ("grouper:processing results...\n"); int data[] = Results.getdata (); for (int number:data) { Finalresult + = number;} System.out.printf ("grouper:total Result:%d.\n", Finalresult);} public static void Main (string[] args) {final int rows=10000;final int numbers=1000;final int search=5;final int Participa nts=5;final int lines_participant=2000; Matrixmock mock = new Matrixmock (ROWS, NUMBERS, SEARCH); Results result = new Results (ROWS); Grouper grouper = new Grouper (result); Cyclicbarrier barrier = new Cyclicbarrier (participants, Grouper); Searcher searchers[] = new searcher[participants];for (int i=0; i<participants; i++) {searchers[i]=new Searcher (i* Lines_participant, (i*lines_participant) +lines_participant, mock, result, 5, barrier); Thread thread=new thread (searchers[i]); Thread.Start ();} System.out.printf ("main:the Main thread has finished.\n");}}


The use of the Java multi-thread ~~~cyclicbarrier class

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.