/* A simple demonstration of race conditions and how to use synchronized to avoid them */ public class MultiThreadedCounter01 implements Runnable { private int n; /* how many times to increment */ private boolean useSynchronized; /* whether to use synchronized methods or not */ private int count = 0; /* we accumulate a count */ /** return the count @return count of how many times incr has been called (supposedly) */ public int getCount() { return count; } public void reset() { count = 0; } /** Increment count as quickly as Java allows. */ public void incr() { count++; /* Equivalent to count = count + 1; */ } /** Increment count as quickly as Java allows. */ public synchronized void incrSync() { count++; /* Equivalent to count = count + 1; */ } /** Create a thread that will increment count n times. @param n How many times to increment @param useSynchronized Whether to use Synchronized methods */ public MultiThreadedCounter01(int n, boolean sync) { this.n = n; this.useSynchronized = sync; } /* run the thread and do the work of incrementing n times */ public void run () { for (int i=0; i