Pages

Wednesday, 1 March 2017

Chapter 30 Exercise 4, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

30.4 (Synchronize threads) Write a program that launches 1,000 threads. Each
thread adds 1 to a variable sum that initially is 0. Define an Integer wrapper
object to hold sum. Run the program with and without synchronization to see
its effect.


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Exercise04 {
 private static Integer sum = 0;
 public static void main(String[] args) {
  ExecutorService executor = Executors.newCachedThreadPool();
 
  for (int i = 0; i < 1000; i++) {
   executor.execute(new AddOne());
  }

  executor.shutdown();

  while (!executor.isTerminated()) {
  }

  System.out.println("sum = " + sum);
 }

 private static class AddOne implements Runnable {
  public void run() {
   sum++;
  }
 }
}

No comments :

Post a Comment