I'm trying to write a program that launches 1000 threads. Each Thread adds 1 to a variable sum that is initially 0. Doing this by passing sum by reference to each thread and I am told to do this using an Integer wrapper object to hold sum.
Code:
public class synchronizedsum {
public static void main(String args[]){
int sum=0;
ExecutorService executor = Executors.newCachedThreadPool();
for(int i=0;i<1000;i++){
executor.execute(new Adder(sum));
}
executor.shutdown();
while(!executor.isTerminated()){
}
System.out.println(sum);
}
private static class Adder implements Runnable{
private int sum;
Adder(int sum){
this.sum = sum;
}
public synchronized void run(){
sum+=1;
}
}
}
I think I've got something wrong cause does not seem to be working.
EDIT: I keep getting output as 0 instead of 1000 that is the problem.
EDIT: I tried doing this seems to give me right output but not sure if it meets the condition of passing sum by reference to each Thread.
CODE:
public class synchronizedsum {
private static Interger obj = new Interger();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for(int i=0;i<1000;i++){
executor.execute(new Add1());
}
executor.shutdown();
while(!executor.isTerminated()){
}
System.out.println(obj.getSum());
}
private static class Interger{
private volatile int sum =0;
private Lock lock = new ReentrantLock();
public void add(int amount){
lock.lock();
try {
sum+=amount;
Thread.sleep(5);
} catch (InterruptedException ex) {
Logger.getLogger(Practice.class.getName()).log(Level.SEVERE, null, ex);
} finally {
lock.unlock();
}
}
public int getSum(){
return sum;
}
}
public static class Add1 implements Runnable{
public void run(){
obj.add(1);
}
}
}