public class SumV2 { // corruption occurs on this shared variable sum: private long sum; private Object lock; // this will give us the ability // to achieve "mutual exclusion" to the sum var public static void main( String[] args ) { SumV2 a = new SumV2(); a.doit(); } public void doit() { sum = 0L; lock = new Object(); // generic int n = 1000000; // assume evenly divisble by 100,000 SumThread[] t = new SumThread[ n / 100000 ]; // divide the summation task into 10 threads (subtasks) for ( int j = 0 ; j < t.length ; j++ ) { t[j] = new SumThread( j * 100000 + 1, ( j + 1 ) * 100000 ); } // 1 - 100,000 // 100,001 - 200,000 // 200,001 - 300,000 // etc. for ( int j = 0 ; j < t.length ; j++ ) { t[j].start(); } try { for ( int j = 0 ; j < t.length ; j++ ) { t[j].join(); } } catch( InterruptedException ex ) { System.err.println( "ERROR: thread interrupted" ); } System.out.println( "SUM 1.." + n + " IS " + sum ); } class SumThread extends Thread { private int m; // sum up values m..n private int n; public SumThread( int m, int n ) { System.out.println( "ADDING " + m + ".." + n + " TO SUM" ); this.m = m; this.n = n; } public void run() { for ( int i = m ; i <= n ; i++ ) { synchronized( lock ) // ensure mutually exclusive access to sum { sum += i; // each of the 10 threads accesses the shared sum var // sum = sum + i; // this statement is being interrupted partway through } } } } }