CyclicBarrier has two constructors:
public CyclicBarrier(int parties, Runnable barrierAction)
public CyclicBarrier(int parties)
The parameter parties refers to how many threads or tasks are allowed to wait until the barrier state; the parameter barrierAction is the content that will be executed when these threads reach the barrier state.
For CyclicBarrier, the most important is the await() method:
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierTest { // Must wait until all three threads call the c.await() method before the program continues to go down static CyclicBarrier c = new CyclicBarrier(3); public static void main(String[] args) throws Exception{ long begin = System.currentTimeMillis(); AddThread th01 = new AddThread(1, 500000, c); AddThread th02 = new AddThread(500001, 1000000, c); th01.start(); th02.start(); // Wait for th01 and th02 to finish executing c.await(); System.out.println(th01.getSum()+th02.getSum()); System.out.println(System.currentTimeMillis()-begin); } } class AddThread extends Thread{ private long sum ; private long begin ; private long end ; private CyclicBarrier cb ; public AddThread(long begin, long end,CyclicBarrier cb) { super(); this.begin = begin; this.end = end; this.cb = cb ; } public long getSum() { return sum; } public long getBegin() { return begin; } public void setBegin(long begin) { this.begin = begin; } public long getEnd() { return end; } public void setEnd(long end) { this.end = end; } @Override public void run(){ try { // can be executed first for(long i=begin;i<=end;i++){ sum += i ; } cb.await(); } catch (InterruptedException e) { e.printStackTrace (); } catch (BrokenBarrierException e) { e.printStackTrace (); } } }