import java.io.*; public class TwoCounters { private static AnInteger total = new AnInteger(0); private static AnInteger count1= new AnInteger(0); private static AnInteger count2= new AnInteger(0); public static void main(String [] args) throws Exception { Counter c1 = new Counter(count1, total); Counter c2 = new Counter(count2, total); Thread t1 = new Thread(c1); Thread t2 = new Thread(c2); t1.start(); t2.start(); System.out.println("main: waiting 10 seconds"); Thread.sleep(10000); // wait 10 seconds System.out.println("main: Count1="+count1.value()+"; Count2="+count2.value()+"; Total="+total.value()); System.out.println("main: Stopping the first counter"); t1.interrupt(); // stop the first counter System.out.println("main: Count1="+count1.value()+"; Count2="+count2.value()+"; Total="+total.value()); System.out.println("main: waiting another 10 seconds"); Thread.sleep(10000); // wait 10 seconds System.out.println("main: Stopping the second counter"); t2.interrupt(); System.out.println("main: Count1="+count1.value()+"; Count2="+count2.value()+"; Total="+total.value()); System.exit(0); } } class Counter implements Runnable { private AnInteger index; // a refererence to an AnInteger object is stored here private AnInteger sum; public Counter(AnInteger i, AnInteger t) { index = i; sum = t; } public void run() { int i; while (true) { for (i=0; i<100; i++) { // do nothing, waste some CPU cycles } if (Thread.interrupted()) { return; } index.increment(); sum.increment(); } } } class AnInteger { private long i; public AnInteger(long x) { i = x; } public void increment() { i = i + 1; } // you can make this a "synchronized" method public long value() { return i;} }