public class Sum { private long sum; public void doit() { sum = 0L; int n = 1000000; // assume this is evenly divisible by 100000 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 // etc. // Start all of the threads 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.exit( 1 ); } System.out.println( "SUM 1.." + n + " IS " + sum ); // sum is a global variable, accessible by all threads } class SumThread extends Thread { private int m; // sum 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++ ) { sum += i; // each of the 10 threads accesses the shared // global variable sum // how is sum+=i compiled down....? // // sum = sum + i; // ===pretend this is bytecode)====> load sum // add i // ----thread-context-switch // store sum } } } public static void main( String[] args ) { Sum a = new Sum(); a.doit(); } }