Sync2.java
// Use a synchronized block to control access to SumArray. class SumArray { private int sum; int sumArray(int[] nums) { sum = 0; // reset sum for(int i=0; i<nums.length; i++) { sum += nums[i]; System.out.println("Running total for " + Thread.currentThread().getName() + " is " + sum); try { Thread.sleep(10); // allow task-switch } catch(InterruptedException exc) { System.out.println("Thread interrupted."); } } return sum; } } class MyThread implements Runnable { Thread thrd; static SumArray sa = new SumArray(); int[] a; int answer; // Construct a new thread. MyThread(String name, int[] nums) { thrd = new Thread(this, name); a = nums; thrd.start(); // start the thread } // Begin execution of new thread. public void run() { System.out.println(thrd.getName() + " starting."); // synchronize calls to sumArray() synchronized(sa) { answer = sa.sumArray(a); } System.out.println("Sum for " + thrd.getName() + " is " + answer); System.out.println(thrd.getName() + " terminating."); } } class Sync2 { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5}; MyThread mt1 = new MyThread("Child #1", a); MyThread mt2 = new MyThread("Child #2", a); try { mt1.thrd.join(); mt2.thrd.join(); } catch(InterruptedException exc) { System.out.println("Main Thread interrupted."); } } }
C:\ece538\java_thread>java Sync2 Child #1 starting. Child #2 starting. Running total for Child #1 is 1 Running total for Child #1 is 3 Running total for Child #1 is 6 Running total for Child #1 is 10 Running total for Child #1 is 15 Running total for Child #2 is 1 Sum for Child #1 is 15 Child #1 terminating. Running total for Child #2 is 3 Running total for Child #2 is 6 Running total for Child #2 is 10 Running total for Child #2 is 15 Sum for Child #2 is 15 Child #2 terminating.
Maintained by John Loomis, updated Mon Nov 19 21:19:54 2012