CyclicBarrier in Java

CyclicBarrier is used to make threads wait for each other. It is used when different threads process a part of computation and when all threads have completed the execution, the result needs to be combined in the parent thread. In other words, a CyclicBarrier is used when multiple thread carry out different sub tasks and the output of these sub tasks need to be combined to form the final output. After completing its execution, threads call await() method and wait for other threads to reach the barrier. Once all the threads have reached, the barriers then give the way for threads to proceed.
```
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
  
class Computation1 implements Runnable
{
    public static int product = 0;
    public void run() {
        product = 2 * 3;
        try {
            Main.newBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
  
class Computation2 implements Runnable
{
    public static int sum = 0;
    public void run() {
        sum = 10 + 20;
        try {
            Main.newBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
  
  
public class Main implements Runnable
{
    public static CyclicBarrier newBarrier = new CyclicBarrier(3);
      
    public static void main(String[] args) {
        new Thread(new Main()).start();
    }
    
    public void run() {
        new Thread(new Computation1()).start();
        new Thread(new Computation2()).start();

        try {
            Main.newBarrier.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Result:" + (Computation1.product + Computation2.sum));
    }
}
```