Java Thread How to - Use ReentrantLock








Question

We would like to know how to use ReentrantLock.

Answer

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//from   ww  w. j a v  a  2 s  . c o m
public class Main {
  public static void main(String[] args) {
    int[] runningThreads = { 0 };
    int[] taskcount = { 10 };
    Lock myLock = new ReentrantLock(true);
    int maxThreadQty = 3;
    while ((taskcount[0] > 0) && (runningThreads[0] < maxThreadQty)) {
      myLock.lock();
      runningThreads[0]++;
      myLock.unlock();
      new Thread("T") {
        public void run() {
          myLock.lock();
          taskcount[0]--;
          runningThreads[0]--;
          myLock.unlock();
        }
      }.start();
    }
  }
}