public class Counter { int value = 0; // Non-atomic increment of value void increment() { int temp = value; //read value HWinterrupt(); value = temp + 1; //write value } // Sometimes an interrupt happens and another thread is // scheduled to run void HWinterrupt() { try { if (Math.random()>0.80) Thread.sleep((int)(Math.random()*500)); } catch(InterruptedException e ) {e.printStackTrace();} } int getValue() { return value; } public static void main(String args[]){ Counter test = new Counter(); Trd t1 = new Trd(test); Trd t2 = new Trd(test); t1.start(); t2.start(); // Wait for the Threads to finish try { t1.join(); t2.join(); } catch(InterruptedException e ) {e.printStackTrace();} System.out.println( "Value should be: 40, but is: " + test.getValue() ); } } class Trd extends Thread { Counter counter; public Trd(Counter c) { counter = c; } // Call increment on the counter 20 times public void run() { for (int i = 0; i < 20; i++) { counter.increment(); } } }