@@ -0,0 +1,1425 @@
+// Use a synchronized block to control access to SumArray.%0Aclass SumArray %7B%0A%09private int sum;%0A%09%0A%09int sumArray(int nums%5B%5D) %7B%0A%09%09sum = 0; // reset sum%0A%09%09%0A%09%09for(int i=0; i%3Cnums.length; i++) %7B%0A%09%09%09sum += nums%5Bi%5D;%0A%09%09%09System.out.println(%22Running total for %22 + Thread.currentThread().getName() + %22 is %22 + sum);%0A%09%09%09try %7B%0A%09%09%09%09Thread.sleep(10); // allow task-switch%0A%09%09%09%7D%0A%09%09%09catch(InterruptedException exc) %7B%0A%09%09%09%09System.out.println(%22Main thread interrupted.%22);%0A%09%09%09%7D%0A%09%09%7D%0A%09%09return sum;%0A%09%7D%0A%7D%0A%0Aclass MyThread implements Runnable %7B%0A%09Thread thrd;%0A%09static SumArray sa = new SumArray();%0A%09int a%5B%5D;%0A%09int answer;%0A%09%0A%09// Construct a new thread.%0A%09MyThread(String name, int nums%5B%5D) %7B%0A%09%09thrd = new Thread(this, name);%0A%09%09a = nums;%0A%09%09thrd.start(); // start the thread%0A%09%7D%0A%09%0A%09// Begin execution of new thread.%0A%09public void run() %7B%0A%09%09int sum;%0A%09%09%0A%09%09System.out.println(thrd.getName() + %22 starting.%22);%0A%09%09%0A%09%09// sunchronize calls to sumArray()%0A%09%09synchronized(sa) %7B%0A%09%09%09answer = sa.sumArray(a);%0A%09%09%7D%0A%09%09System.out.println(%22Sum for %22 + thrd.getName() + %22 is %22 + answer);%0A%09%09%0A%09%09System.out.println(thrd.getName() + %22 terminating.%22);%0A%09%7D%0A%7D%0A%0Aclass SyncBlock %7B%0A%09public static void main(String args%5B%5D) %7B%0A%09%09int a%5B%5D = %7B1, 2, 3, 4, 5%7D;%0A%09%09%0A%09%09MyThread mt1 = new MyThread(%22Child #1%22, a);%0A%09%09MyThread mt2 = new MyThread(%22Child #2%22, a);%0A%09%09%0A%09%09try %7B%0A%09%09%09mt1.thrd.join();%0A%09%09%09mt2.thrd.join();%0A%09%09%7D catch(InterruptedException exc) %7B%0A%09%09%09System.out.println(%22Main thread interrupted.%22);%0A%09%09%7D%0A%09%7D%0A%7D%0A

Use a synchronized block