Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Concepts

Authors: David M. Kroenke

1st Edition

0130086509, 978-0130086501

More Books

Students also viewed these Databases questions

Question

How do Data Types perform data validation?

Answered: 1 week ago

Question

How does Referential Integrity work?

Answered: 1 week ago