The code copy is as follows:
package com.yao;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
/**
* CyclicBarrier is similar to CountDownLatch, and it is also a counter.
* The difference is that the number of CyclicBarrier is called CyclicBarrier.await() to enter the waiting number.
* When the number of threads reaches the number specified at the initial time of CyclicBarrier, all threads entering the waiting state are awakened and continue.
* CyclicBarrier, just like its name, can be regarded as an obstacle.
* All threads must be arrived before they can pass this obstacle together.
* CyclicBarrier can also have a Runnable parameter at the beginning.
* After the number of CyclicBarrier reaches, all other threads are executed before they are awakened.
*/
public class CyclicBarrierTest {
public static class ComponentThread implements Runnable {
CyclicBarrier barrier;// Counter
int ID;// Component ID
int[] array;// Data array
// Construct 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 for Barrier here
System.out.println("Component " + ID + " sleep...");
barrier.await();
System.out.println("Component " + ID + " awakened...");
// Calculate the current and subsequent values in the data array
int result = array[ID] + array[ID + 1];
System.out.println("Component " + ID + " result: " + result);
} catch (Exception ex) {
}
}
}
/**
* Test the usage of CyclicBarrier
*/
public static void testCyclicBarrier() {
final int[] array = new int[3];
CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {
// Execute when all threads arrive at Barrier
public void run() {
System.out.println("testCyclicBarrier run...");
array[2] = array[0] + array[1];
}
});
// Start the 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();
}
}