Copy Code code as follows:
Package Com.yao;
Import Java.util.Random;
Import Java.util.concurrent.CyclicBarrier;
/**
* Cyclicbarrier similar to Countdownlatch is also a counter,
* The difference is cyclicbarrier number is called cyclicbarrier.await () into the waiting number of threads,
* When the number of threads reaches the number specified in the initial cyclicbarrier, all threads that enter the wait state are awakened and continue.
* Cyclicbarrier, like the meaning of its name, can be seen as an obstacle,
* All threads must be aligned to pass this barrier together.
* Cyclicbarrier can also take a runnable parameter at the initial time,
* This runnable task is executed before all other threads are awakened, after the number of Cyclicbarrier is reached.
*/
public class Cyclicbarriertest {
public static class Componentthread implements Runnable {
Cyclicbarrier barrier;//counter
int ID; Component identification
Int[] Array; Array of data
Construction method
Public Componentthread (Cyclicbarrier barrier, int[] array, int ID) {
This.barrier = barrier;
This.id = ID;
This.array = array;
}
public void Run () {
try {
Array[id] = new Random (). Nextint (100);
System.out.println ("Component" + ID + "generates:" + array[id]);
Wait here for the barrier place.
System.out.println ("Component" + ID + "sleep ...");
Barrier.await ();
System.out.println ("Component" + ID + "awaked ...");
Calculates the current and subsequent values in an array of data
int result = Array[id] + array[id + 1];
System.out.println ("Component" + ID + "Result:" + result);
catch (Exception ex) {
}
}
}
/**
* Test the use of Cyclicbarrier
*/
public static void Testcyclicbarrier () {
Final int[] array = new INT[3];
Cyclicbarrier barrier = new Cyclicbarrier (2, New Runnable () {
Executed when all threads have reached barrier
public void Run () {
System.out.println ("Testcyclicbarrier run ...");
ARRAY[2] = array[0] + array[1];
}
});
Start thread
New Thread (New Componentthread (barrier, array, 0)). Start ();
New Thread (New Componentthread (barrier, array, 1)). Start ();
}
public static void Main (string[] args) {
Cyclicbarriertest.testcyclicbarrier ();
}
}