Use the example for Java threads concurrent with the cyclicbarrier class

  • 2020-04-01 02:49:08
  • OfStack


package com.yao;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
 public static class ComponentThread implements Runnable {
  CyclicBarrier barrier;//counter
  int ID; //Component identification
  int[] array; //The data array
  //A constructor
  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
    System.out.println("Component " + ID + " sleep...");
    barrier.await();
    System.out.println("Component " + ID + " awaked...");
    //Calculates 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) {
   }
  }
 }
 
 public static void testCyclicBarrier() {
  final int[] array = new int[3];
  CyclicBarrier barrier = new CyclicBarrier(2, new Runnable() {
   //Execute when all threads have reached the Barrier
   public void run() {
    System.out.println("testCyclicBarrier run...");
    array[2] = array[0] + array[1];
   }
  });
  //Starting a 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();
 }
}


Related articles: