import java.util.*; // a simple counter class class Counter { private int value; public Counter() { value = 0; } public synchronized void increment() { int current_value = value; try { Thread.sleep(1); } catch (InterruptedException e) { } int new_value = current_value + 1; value = new_value; } public int getValue() { return value; } } // a thread class to increment a counter by a certain amount in parallel class IncThread extends Thread { private Counter counter; private int amount; public IncThread(Counter c, int amt) { counter = c; amount = amt; } @Override public void run() { for (int i = 0; i < amount; i++) { counter.increment(); } } } public class Sharing2 { public static void main(String args[]) { // create a counter Counter counter = new Counter(); // make some threads increment the counter IncThread [] threads = new IncThread[100]; for (int i = 0; i < 100; i++) { threads[i] = new IncThread(counter, 5); } // start them all for (int i = 0; i < 100; i++) { threads[i].start(); } // wait for them to finish try { for (int i = 0; i < 100; i++) { threads[i].join(); } } catch (InterruptedException e) { } // get the value System.out.println(counter.getValue()); } }