/* Taken from "The Art of Multiprocessor Programming" by Herlihy, Maurice and Shavit, Nir and slightly modified. */ import java.util.concurrent.locks.ReentrantLock ; public class CounterLock { private int value ; private ReentrantLock mutex = new ReentrantLock() ; // to protect critical section public CounterLock (int c) { // constructor value = c ; } // get method for the value public int getValue() { return value; } // increment and return prior value public int getAndIncrement() { mutex.lock() ; // enter critical section int temp = 0 ; try { // start of critical section temp = value ; System.out.println("temp: " + temp); value = temp + 1 ; // end of critical section } finally { mutex.unlock() ; // exit critical section } return temp ; } public static void main (String args[]) throws InterruptedException { Thread[] thread = new Thread[200] ; CounterLock counter = new CounterLock(0) ; // shared by all threads // create threads for (int i = 0; i < thread.length; i++) { thread[i] = new Thread(new Runnable() { public void run() { int n = counter.getAndIncrement(); } }) ; } // start threads for (int i = 0; i < thread.length; i++) { thread[i].start() ; } // wait for threads to finish for (int i = 0; i < thread.length; i++) { thread[i].join(); } System.out.println("final value of counter: "+ counter.getValue()); } }