I have created a program which creates 1000 threads and each threads adds 1 in to a variable sum. My problem is the output i get is only 1s.
Here is the program:
class Threading implements Runnable{
T6_Q1 sumObject=new T6_Q1();
Thread t;
Threading(){
t=new Thread(this);
t.start();
}
@Override
public void run() {
setSumValue();
System.out.println(sumObject.getSum());
}
public void setSumValue(){
Integer value=sumObject.getSum().intValue()+1;
sumObject.setSum(value);
}
}
public class T6_Q1
{
Integer sum =new Integer(0);
public void setSum(int value){
this.sum=new Integer(value);
}
//method to get the sum value
public Integer getSum(){
return this.sum;
}
public static void main(String[] args) {
//launches 1000 threads
for(int i=1;i<=1000;i++)
{
new Threading();
}
}
}
Even if i synchronized the setSumValue method i only get 1s. What am i doing wrong here ? (Am new to threading so still bit hard to understand the errors)
Thank you for your time.