(Synchronize threads) Write a program that launches 1,000 threads. Each thread
adds 1 to a variable sum that initially is 0. You need to pass sum by reference to
each thread. In order to pass it by reference, define an Integer wrapper object to
hold sum. Run the program with and without synchronization to see its effect.
import java.util.concurrent.*;
public class threads {
private Integer sum = new Integer(0);
public static void main(String[] args) {
threads test = new threads();
System.out.println("What is sum ? " + test.sum);
}
public threads() {
ExecutorService executor = Executors.newFixedThreadPool(1000);
for (int i = 0; i < 1000; i++) {
executor.execute(new SumTask());
}
executor.shutdown();
while(!executor.isTerminated()) {
}
}
class SumTask implements Runnable {
public void run() {
int value = sum.intValue() + 1;
sum = new Integer(value);
}
}
}