Question
(MultiThreading/Parallel processing) import java.util.concurrent.*; public class Midterm_3 { private Integer sum = new Integer(0); public static void main(String[] args) { Midterm_3 test = new Midterm_3();
(MultiThreading/Parallel processing)
import java.util.concurrent.*;
public class Midterm_3 {
private Integer sum = new Integer(0);
public static void main(String[] args) {
Midterm_3 test = new Midterm_3();
System.out.println("What is sum ? " + test.sum);
}
public Midterm_3() {
ExecutorService executor = Executors.newFixedThreadPool(100);
Task task = new Task();
for (int i = 0; i < 15; i++) {
executor.execute(task);
}
executor.shutdown();
while(!executor.isTerminated()) {
}
}
class Task implements Runnable {
public void run() {
sum++;
}//end run
}//end Task
}//end Midterm_3
Running this code does not always give the expected result of 15. Why not, and what change can be made to the code so that it will perform as expected?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started