public class Count2000 implements Runnable { static int count = 0; public static void main(String[] args) { Count2000 me = new Count2000(); me.startTwoThreads(); } private void startTwoThreads() { Thread firstThread = new Thread(this); Thread secondThread = new Thread(this); firstThread.start(); secondThread.start(); } // add 1 to a static, shared variable (named count) 1000 times private void countUp() { for(int i = 0; i < 1000; i++) { // With the next line uncommented, the final total will be 2000 // With it commented, the final total is usually much smaller, and // it can even be *less* than the count shown by the // FIRST terminating thread // Note the program runs slower when synchronized //synchronized(this) { int x = count; try { // simulate computing a result (0 to 2 ms) Thread.sleep((int)(Math.random() * 3)); } catch ( InterruptedException e ) { // it would be *very* surprising if the exception were thrown... e.printStackTrace(); } count = x + 1; // the following also creates bad counts, but only on multi-core systems // and the error amount is much smaller //count += 1; } } } public void run() { System.out.println("Running a thread."); countUp(); // display result when thread terminates System.out.println("Thread terminating with count = " + count); } }