Question: java. Write a program that launches 1,000 threads. Each thread adds 1 to a variable named sum that initially is 0. You need to pass
java. Write a program that launches 1,000 threads. Each thread adds 1 to a variable named 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.
Hint: Create Runnable class first. sum should NOT be a local variable in the Runnable class. Run the program with synchronization to see its effect. Synchronization should make the use of shared variable sum thread safe.
This is the program without synchronization
public class Main { public static void main(String[] args) { Unsync totalSum = new Unsync(); for (int i =0; i < 1000; i++) { Thread newThread = new Thread(new Threads(totalSum)); newThread.start(); } } } public class Threads implements Runnable { private Unsync sumInstance; public Threads(Unsync sumInstance) { this.sumInstance = sumInstance; } @Override public void run() { sumInstance.add(1); } }
public class Unsynchronization { private double Sum; public Unsync() { Sum = 0; } public void add(double amount) { Sum += amount; System.out.println("The sum is now =" + Sum); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
