Write a program that launches 50 threads. Each thread should add one to a variable named sum that is initialized to zero. Run the program with and without synchronization to see its effect.
IN JAVA PLEASE
ALSO PLEASE SPECIFY HOW TO RUN THIS PROGRAM - WITH AND WITHOUT SYNCHRONIZATION
THANK YOU
Program without Synchronization
class Demo implements Runnable {
static int sum = 0;// static sum variable
@Override
public void run() {
++sum;// adding 1 to sum
}
}
public class Test {
public static void main(String[] args) {
Thread[] ar = new Thread[50];//
creating an array of 50 threads
for (int i = 0; i < 50; i++)
{
// initilizing
the array
ar[i] = new
Thread(new Demo());
}
long start = System.nanoTime();//
getting start time
for (int i = 0; i < 50; i++)
{
ar[i].start();//
starting the threads
}
long time = System.nanoTime() -
start;// calculating time taken in nanoseconds
System.out.printf("Took %.1f ms to
complete the task\n", time / 1e6);// showing time in
milliseconds
System.out.println("Sum: " +
Demo.sum);// showing sum value
}
}
Program with Synchronization
class Demo implements Runnable {
static int sum = 0;// static sum variable
@Override
public synchronized void run() {//synchronized
method
++sum;// adding 1 to sum
}
}
public class Test {
public static void main(String[] args) {
Thread[] ar = new Thread[50];//
creating an array of 50 threads
for (int i = 0; i < 50; i++)
{
// initilizing
the array
ar[i] = new
Thread(new Demo());
}
long start = System.nanoTime();//
getting start time
for (int i = 0; i < 50; i++)
{
ar[i].start();//
starting the threads
}
long time = System.nanoTime() -
start;// calculating time taken in nanoseconds
System.out.printf("Took %.1f ms to
complete the task\n", time / 1e6);// showing time in
milliseconds
System.out.println("Sum: " +
Demo.sum);// showing sum value
}
}
Get Answers For Free
Most questions answered within 1 hours.