Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Synchronize threads. Write a program that launches 1,000 threads. Each thread ad

ID: 3863729 • Letter: S

Question

Synchronize threads. Write a program that launches 1,000 threads. Each thread adds 1 to a variable sum that initially is 0. Define an Integer wrapper object to hold sum.

Create two versions of the program with and without synchronization to see the different effects.

Hint: In the synchronized version, the sum will always be 1000 at the end. In the unsynchronized version, the sum will most likely be a number other than 1000 at the end.

Upload the code files (TestSynchronizedSum.java and TestUnSynchronizedSum.java) as your submission.

Explanation / Answer

TestSynchronizedSum.java

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestSynchronizedSum {
Integer sum=new Integer(0);

public TestSynchronizedSum(){
ExecutorService e=Executors.newFixedThreadPool(1000);
Sum s = new Sum();
for(int i=0;i<1000;i++){
e.execute(s);
}
e.shutdown();

while(!e.isTerminated()){

}
System.out.println(sum);
}
public static void main(String[]args){
new TestSynchronizedSum();
}

class Sum implements Runnable{

@Override
public void run() {
thred();
}
public synchronized void thred(){
sum=sum+1;
}
}
}

TestUnSynchronizedSum.java


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestUnSynchronizedSum {
Integer sum=new Integer(0);

public TestUnSynchronizedSum(){
ExecutorService e=Executors.newFixedThreadPool(1000);
Sum s = new Sum();
for(int i=0;i<1000;i++){
e.execute(s);
}
e.shutdown();

while(!e.isTerminated()){

}
System.out.println(sum);
}
public static void main(String[]args){
new TestUnSynchronizedSum();
}

class Sum implements Runnable{

@Override
public void run() {
thred();
}
public void thred(){
sum=sum+1;
}
}
}