Java Thread How to - Suspend Thread using java.util.concurrent








Question

We would like to know how to suspend Thread using java.util.concurrent.

Answer

import java.util.concurrent.CyclicBarrier;
// w  ww  .j a  v  a  2  s. c om
public class Main {
  public static void main(String[] args) {
    CyclicBarrier barrier = new CyclicBarrier(2);
    new Thread() {
      @Override
      public void run() {
        try {
          System.out.println("in thread, before the barrier");
          barrier.await();
          System.out.println("in thread, after the barrier");
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }.start();

    try {
      System.out.println("main thread, before barrier");
      barrier.await();

      System.out.println("main thread, after barrier");
    } catch (Exception exc) {
      exc.printStackTrace();
    }
  }
}

The code above generates the following result.