/* Based on example from "The Art of Multiprocessor Programming" by Herlihy, Maurice and Shavit, Nir and slightly modified. */ public class Counter { private int value ; public Counter (int c) { // constructor value = c ; } // increment and return prior value public int getAndIncrement() { // start of critical section int temp = value ; System.out.println("temp = " + temp); value = temp + 1 ; // end of critical section return temp ; } // get method for the value public int getValue() { return value; } public static void main (String args[]) throws InterruptedException { Thread[] thread = new Thread[200] ; Counter counter = new Counter(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(); } }) ; } // starting the threads for (int i = 0; i < thread.length; i++) { thread[i].start() ; } // waiting for threads to finish for (int i = 0; i < thread.length; i++) { thread[i].join(); } System.out.println("final value of counter: "+ counter.getValue()); } }