public class WhySynchronized { private final static int TESTS = 1000; /* * Run this program several times and look at the result. */ public static void main(String[] args) { int[] values = new int[3]; for ( int i = 0; i < TESTS; ++i ) { // data container TheThread.Data d = new TheThread.Data(); // create threads Thread t1 = new TheThread(d); Thread t2 = new TheThread(d); // start threads t1.start(); t2.start(); try { // wait for threads to complete t1.join(); t2.join(); } catch (InterruptedException ignored) { } // count values values[d.a]++; } System.out.println( "After adding 1 twice, repeating "+TESTS+" times, the result was:\n"+ " * 1: "+values[1]+" times\n"+ " * 2: "+values[2]+" times"); } } class TheThread extends Thread { private final Data _d; public TheThread(Data d) { _d = d; } public void run() { _d.a++; } /** * Inner data class. */ public static class Data { public int a = 0; } }