public class Parallel {
public static void main(String args[]) {
MyThread[] myThreadArray = new MyThread[MyThread.numOfThread];
Thread[] threadArray = new Thread[MyThread.numOfThread];
double result = 0;
double startTime = System.currentTimeMillis();
for (int i = 0; i < MyThread.numOfThread; i++) {
myThreadArray[i] = new MyThread(i);
threadArray[i] = new Thread(myThreadArray[i]);
}
for (int i = 0; i < MyThread.numOfThread; i++) {
threadArray[i].start();
}
for (int i = 0; i < MyThread.numOfThread; i++) {
try {
threadArray[i].join();
} catch (Exception e) {
}
}
for (int i = 0; i < MyThread.numOfThread; i++) {
result += myThreadArray[i].result;
}
double totalTime = System.currentTimeMillis() - startTime;
System.out.println(MyThread.numOfThread + "线程计算");
System.out.println("PI = " + result);
System.out.println("N取 " + MyThread.N + " 时, 耗时 " + totalTime + " 毫秒");
}
}
class MyThread implements Runnable {
static final int N = 1000000000;
static final int numOfThread = 12;
int n; // 第n个线程
public double result;
MyThread(int n) {
this.n = n;
}
public void run() {
for (int i = n; i <= N; i += numOfThread) {
result += 4 / (1 + Math.pow((i + 0.5) / N, 2)) / N;
}
}
}
评论0