I have been trying to calculate the value of pi using Monte Carlo simulation in parallel.
So far, I have created threads, and generated the random points, but I'm not able to return those generated points back from the threads to the main thread.
How to tackle this problem ?
Below is the code I have written
import java.util.*;
class MyThread extends Thread{
int points;
int insidePoints;
public MyThread(int insidePoints, int points){
this.points = points;
this.insidePoints = insidePoints;
}
// simulating monte carlo to generate points and check which are inside the circle
public void run(){
int prec = 1000000;
Random rand = new Random();
for( int i=0 ; i < points ; ++i){
double x = (double)rand.nextInt(prec+1)/(double)prec;
double y = (double)rand.nextInt(prec+1)/(double)prec;
if( (x*x + y*y) <= 1){
++insidePoints;
}
}
System.out.println("Thread " + Thread.currentThread().getId() + " running and Inside points are" + insidePoints);
}
public int getCount(){
return this.insidePoints;
}
}
public class A{
public static void main(String[] args){
int totalPoints = 1000000;
int insidePoints = 0;
int threadsToBeUsed = 1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the value of Threads : ");
threadsToBeUsed = scan.nextInt();
try{
int eachThreadPoints = totalPoints/threadsToBeUsed;
Thread[] thread = new Thread[threadsToBeUsed];
for(int i = 0; i < threadsToBeUsed ; ++i){
if( i == (threadsToBeUsed-1)){
eachThreadPoints += (totalPoints)%eachThreadPoints ;
}
MyThread myT = new MyThread(insidePoints, eachThreadPoints);
thread[i] = new Thread(myT);
thread[i].start();
}
for( int i=0; i < threadsToBeUsed; ++i)
thread[i].join();
System.out.println("Number of inside points :" + insidePoints);
System.out.println("Pi/4 = " + (double)insidePoints/(double)totalPoints);
System.out.println("Pi = " + 4*(double)insidePoints/(double)totalPoints);
} catch(Exception e){
System.out.println(e);
System.exit(1);
}
}
}