Java Concurrency Synchronization helper class Cyclicbarrier

Source: Internet
Author: User

Cyclicbarrier Meaning:

The fence allows two or more threads to synchronize at a certain point in the collection. When a thread arrives at the collection point, it calls the await () method to wait for the other thread. After the thread calls 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 wakes up all the waiting threads and then the threads continue to execute. Cyclicbarrier can pass in another Runnable object as an initialization parameter. When all the threads have reached the rendezvous 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 (two-dimensional array). The matrix is divided into subsets, and each subset is given to a thread to look up. When all threads have been found, the final thread rollup results are presented.
Lookup class: Find the specified number in a subset, locate and then store the result and call the await () method to place hibernation wait for the arrival of 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, list<result> result, cyclicbarrier barrier, int row, int searchnmu) {This.barri
    ER = barrier;
    This.submock = Submock;
    This.result = result;
    This.row = row;
This.searchnmu = SEARCHNMU; @Override public void Run () {System.out.printf ("%s:processing lines from%d. \ n"), Thread.CurrentThread (). GetName
    (), row);
            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 {

    //row
    int row;
    column
    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: Summarize the results found by each searcher:

Import java.util.List;

public class Grouper implements Runnable {

private list<result> result;

Int[][] mock;

Public grouper (list<result> result, int[][] mocks) {
    This.result = result;
    This.mock = mock;
}

@Override public
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");
}

Main function, how to combine searcher and grouper classes ...

Import java.util.ArrayList;
Import java.util.List;

Import Java.util.concurrent.CyclicBarrier;

    public class Cyclicbarriermain {public static void main (string[] args) {//data to be searched final int SEARCH = 5;
            Declaration of matrices 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: Thread synchronization number, 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 noted
the await () method of calling Cyclicbarrier after a task completes the wait. When all threads arrive at the rendezvous point, the fence calls the incoming Runnable object for final execution.
Difference from Countdownlatch:
Accept a runnable type of object as a subsequent execution after all threads arrive at the collection point
does not display the call Countdown () method
Countdownlatch can be used only once, cyclicbarrier multiple threads to use
scenarios
to do tasks, wait until the rendezvous point synchronization to the following thread to do the rollup
it video access

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.