用Java编写求π包含并行和串行
时间: 2024-03-08 17:47:04 浏览: 59
Java串行程序并行化执行
下面是Java编写的串行和并行求π的示例代码:
串行求π:
```java
public class SerialPi {
public static void main(String[] args) {
int n = 10000000;
double pi = 0;
int sign = 1;
for (int i = 1; i <= n; i += 2) {
pi += sign * 4.0 / i;
sign = -sign;
}
System.out.println("π ≈ " + pi);
}
}
```
并行求π:
```java
public class ParallelPi {
public static void main(String[] args) throws InterruptedException {
int n = 10000000;
int numThreads = 4;
double pi = 0;
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
final int threadId = i;
threads[i] = new Thread(() -> {
double subSum = 0;
int sign = (threadId % 2 == 0) ? 1 : -1;
for (int j = threadId + 1; j <= n; j += numThreads) {
subSum += sign * 4.0 / j;
sign = -sign;
}
synchronized (ParallelPi.class) {
pi += subSum;
}
});
threads[i].start();
}
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
System.out.println("π ≈ " + pi);
}
}
```
这里使用的方法和参数与之前提到的示例代码相同,区别在于并行计算使用了多个线程来计算级数的不同部分,并使用 synchronized 关键字来保证各个线程对共享变量 pi 的访问是安全的。
阅读全文