/** *

This program demonstrates the use of Java monitor through * the "synchronized" method.

* *

When tring out the program, if the "synchronized" keyword * is commented out in the Counter.increment() method, then * the Counter object is not protected by the monitor, the resulting * value of the counter will be incorrect, especially with large * number of threads (e.g., 500).

* *

For CSCI 315 class demonstration.

* * @author Xiannong Meng * @date 09-27-2013 */ public class CounterDemo extends Thread { public static final int SIZE = 50; public static int finishCount = 0; /* The test program */ public static void main(String [] args) { CounterDemo demo = new CounterDemo(); demo.runDemo(); } public void runDemo() { Counter b = new Counter(0); // Shared counter among threads Worker w[] = new Worker[SIZE]; // create an array of threads for (int i = 0; i < SIZE; i ++) w[i] = new Worker(b, i); // create each Worker() for (int i = 0; i < SIZE; i ++) w[i].start(); // start each thread // busy waiting for all threads to finish, // didn't find a better and easier mechanism // should be improved while (finishCount < SIZE) { try { Thread.sleep(10); } catch (InterruptedException e) {} } System.out.println("value after " + b.get()); } } class Worker extends Thread { private Counter value; private int id; Worker(Counter b, int id) { value = b; this.id = id;} public void run() { for(int i = 0; i < 10; i++) { this.value.increment(); } CounterDemo.finishCount ++; // System.out.println("value " + this.value.get() + " in thread " + this.id); } } class Counter { private int count; Counter(int init) { this.count = init; } /* * Toggle between "synchronized" or not one would test * the effects of the monitor. * Without "synchronized" the result will be incorrect. */ public synchronized void increment() { // public void increment() { this.count ++; } public int get() { return this.count; } }