I have below program to calculate value of Pi using threads, for simplicity I kept to maximum of 2 threads.
public class PiCalculator {
class Pi implements Runnable{
int start;
int end;
volatile double result;
public Pi(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for(int i = start; i < end; i++) {
result += Math.pow(-1, i) / ((2 * i) + 1);
}
System.out.println(Thread.currentThread().getName() + " result =" + result);
}
public double getResult(){
return result;
}
}
public static void main(String[] args) throws InterruptedException {
int maxThreads = 2;
int maxValuePerThread = 1000 / maxThreads;
int start = 0;
int end = maxValuePerThread;
double resultOut = 0d;
PiCalculator pc = new PiCalculator();
for(int i = 0; i < 2; i++) {
Pi p = pc.new Pi(start, end);
Thread t = new Thread(p);
t.setName("thread" + i);
t.start();
t.join();
start = start + end;
end = end + maxValuePerThread;
resultOut += p.getResult();
}
System.out.println("Final result = " + resultOut);
}
}
1) Why am I getting below result? What am I doing wrong?
thread0 result =0.7848981638974463
thread1 result =2.4999956250242256E-4
Final result = 0.7851481634599486
The Pi value is 3.14..... right?
2) When I change the
volatile double result;
to
double result;
I still get the same output, why is that so?