Question
Write a program that launches 1,000 threads. Each thread adds1 to a variable named sum that initially is 0. You need to pass sum by
Write a program that launches 1,000 threads. Each thread adds1 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. Run the program with and without synchronization to see its effect.
Hint: Create Runnable class first. sum should NOT be a local variable in the Runnable class.
Synchronization should make the use of shared variable sum thread safe.
Here is my code. I keep getting 1 as a return. I think it should be 996.
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class SumSync {
private static Sumadd a = new Sumadd();
public static void main(String[] args)
{
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++)
{
executor.execute(new SumRunner());
}
executor.shutdown();
while (executor.isTerminated())
{
}
System.out.println("The sum at 1000 threads is:" + a.getValue());
}
private static class SumRunner implements Runnable
{
public synchronized void run()
{
a.adding(1);
}
}
private static class Sumadd
{
private static Lock lock = new ReentrantLock();
private Integer sum = 0;
public Integer getValue()
{
return sum;
}
private void adding(int amount)
{
lock.lock();
sum += amount;
try
{
Thread.sleep(500);
}
catch(InterruptedException ex)
{
}
finally {
lock.unlock();
}
}
}
}
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