计算π的多线程java
时间: 2023-11-27 07:42:45 浏览: 83
计算π的多线程java程序可以使用Runnable接口来实现。下面是一个示例程序:
```java
public class PiCalculator implements Runnable {
private static final int numSteps = 10000000; // 迭代次数
private int start;
private int end;
private double sum;
public PiCalculator(int start, int end) {
this.start = start;
this.end = end;
this.sum = 0.0;
}
public double getSum() {
return sum;
}
@Override
public void run() {
double step = 1.0 / numSteps;
for (int i = start; i < end; i++) {
double x = (i + 0.5) * step;
sum += 4.0 / (1.0 + x * x);
}
}
public static void main(String[] args) {
int numThreads = 3; // 并行线程数
int stepsPerThread = numSteps / numThreads;
Thread[] threads = new Thread[numThreads];
PiCalculator[] calculators = new PiCalculator[numThreads];
// 创建并启动线程
for (int i = 0; i < numThreads; i++) {
int start = i * stepsPerThread;
int end = (i + 1) * stepsPerThread;
calculators[i] = new PiCalculator(start, end);
threads[i] = new Thread(calculators[i]);
threads[i].start();
}
// 等待所有线程执行完毕
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 汇总结果
double sum = 0.0;
for (PiCalculator calculator : calculators) {
sum += calculator.getSum();
}
double pi = sum / numSteps;
System.out.println("PI(π) = " + pi);
}
}
```
阅读全文