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 a

ID: 3548900 • Letter: #

Question

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

adds 1 to a variable 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


I will post my code..   THe problem I am getting is that I am getting


At Thread 6 Sum= 1 ,

At Thread 1 Sum= 3 ,

At Thread 9 Sum= 3 ,

At Thread 2 Sum= 3 ,

At Thread 3 Sum= 1 ,


I should be getting


At Thread 0 Sum= 0 ,

At Thread 1 Sum= 1 ,

At Thread 2 Sum= 2 ,

etc.....


here is the code


package pkg32.pkg4;


import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;


/**

*

* @author Coxxie

*/

public class Main

{


    /**

     * @param args the command line arguments

     */

    private static Integer sum = new Integer(0);


    public static void main(String[] args)

    {

        ExecutorService executor = Executors.newFixedThreadPool(1000);


        for (int i = 0; i <= 1000; i++)

        {

            executor.execute(new SumTask2(i));

        }

        executor.shutdown();

    }


    static class SumTask2 implements Runnable

    {

        int id;

        SumTask2(int n)

        {

            id = n;

        }

        public synchronized void run()

        {

            sum++;

            System.out.println("At Thread " + id + " Sum= " + sum + " , ");

        }

    }

}

Explanation / Answer

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

public class Threads2 {
private Integer sum = new Integer(0);



public synchronized static void main(String[] args) {

Threads2 test = new Threads2();
System.out.println("What is sum ?" + test.sum);
}

public Threads2(){
ExecutorService executor = Executors.newFixedThreadPool(1000);

System.out.println("With SYNCHRONIZATION........");
for(int i = 1; i <= 1000; i++){
executor.execute(new SumTask2());
System.out.println("At Thread " + i +" Sum= " + sum + " , ");
}


executor.shutdown();

while(!executor.isTerminated()){
}
}


class SumTask2 implements Runnable{
public synchronized void run(){
int value = sum.intValue() + 1;
sum = new Integer(value);
}
}
}