The answer should always be 500, but it keeps getting changed
I ran 1000 threads, if the thread is odd it should decrements the sum using a loop 100000 times, and if even increment 100001 times.
The answer keeps getting changed though i used the join method, any suggestions?
package softwaredesign.assignment1;
public class SoftwareDesignAssignment1 {
public static class T implements Runnable{
int e=0;
T(int z){
e=z;
}
public void run(){
if(e==1){
for(int i=0;i< 100001;i++)
SoftwareDesignAssignment1.sum+=e;
}
else{
for(int i=0;i< 100000;i++)
SoftwareDesignAssignment1.sum=sum+e;
}
}
}
public static int sum=0;
public static void main(String[] args) throws InterruptedException {
Thread[] t=new Thread[1000];
for(int i=0;i<1000;i++){
if(i%2==0)
t[i]=new Thread(new T(1));
else
t[i]=new Thread(new T(-1));
}
for(Thread tt:t){
tt.start();
}
for(Thread tt:t){
tt.join();
}
System.out.print(sum);
}
}