Java Thread How to - Use CountDownLatch to lock variable








Question

We would like to know how to use CountDownLatch to lock variable.

Answer

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
//w w  w.j av a2s  .co  m
public class Main implements Runnable {
  static int NUM_THREADS = 25;
  CountDownLatch cdl1 = new CountDownLatch(NUM_THREADS);
  int myValue = 0;
  AtomicInteger count = new AtomicInteger(0);
  public static void main(String[] args) {
    Main main = new Main();
    for (int i = 0; i < NUM_THREADS; i++)
      new Thread(main).start();
  }
  public void run() {
    int i = count.incrementAndGet();
    myValue = i;
    cdl1.countDown();
    try {
      cdl1.await();
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    }
    if (myValue != i)
      System.out.println("Bar not equal to i");
    else
      System.out.println("Bar equal to i");
  }
}

The code above generates the following result.