java串行、并行、并发计算π
时间: 2023-08-11 10:06:59 浏览: 230
并行计算三种方式计算π
首先,计算π的方法主要有两种:蒙特卡罗方法和数学公式法。这里以数学公式法为例,介绍Java的串行、并行、并发计算π的实现方法。
1. 串行计算π
首先,我们可以使用莱布尼茨级数公式来计算π。该公式的计算公式为:π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... + (-1)^(n+1)/(2n-1)。我们可以通过循环来计算这个公式,直到达到预设的精度。下面是一个Java串行计算π的示例代码:
```
public class SerialPi {
public static void main(String[] args) {
long start = System.currentTimeMillis();
int n = 100000000; // 循环次数
double sum = 0.0;
for (int i = 1; i <= n; i++) {
double item = (i % 2 == 1 ? 1 : -1) * 1.0 / (2 * i - 1);
sum += item;
}
double pi = 4 * sum;
long end = System.currentTimeMillis();
System.out.println("Pi: " + pi);
System.out.println("Time: " + (end - start) + "ms");
}
}
```
2. 并行计算π
对于计算π这种密集型的计算任务,我们可以使用并行计算来提高计算效率。Java中提供了多线程的机制来实现并行计算。我们可以将计算任务分配给多个线程来同时进行计算,最后将结果进行合并。下面是一个Java并行计算π的示例代码:
```
public class ParallelPi {
private static final int NTHREADS = 4; // 线程数量
private static final int N = 100000000; // 循环次数
private static double[] sumArray = new double[NTHREADS];
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Thread[] threads = new Thread[NTHREADS];
for (int i = 0; i < NTHREADS; i++) {
int id = i;
threads[i] = new Thread(() -> {
double sum = 0.0;
for (int j = id; j < N; j += NTHREADS) {
double item = (j % 2 == 1 ? 1 : -1) * 1.0 / (2 * j - 1);
sum += item;
}
sumArray[id] = sum;
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
double sum = 0.0;
for (double item : sumArray) {
sum += item;
}
double pi = 4 * sum;
long end = System.currentTimeMillis();
System.out.println("Pi: " + pi);
System.out.println("Time: " + (end - start) + "ms");
}
}
```
3. 并发计算π
Java中的并发计算可以通过线程池来实现。线程池可以有效地管理线程的数量,避免线程创建和销毁的开销。下面是一个Java并发计算π的示例代码:
```
public class ConcurrentPi {
private static final int NTHREADS = 4; // 线程数量
private static final int N = 100000000; // 循环次数
private static double[] sumArray = new double[NTHREADS];
public static void main(String[] args) throws InterruptedException, ExecutionException {
long start = System.currentTimeMillis();
ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);
List<Future<Double>> futures = new ArrayList<>();
for (int i = 0; i < NTHREADS; i++) {
int id = i;
futures.add(executor.submit(() -> {
double sum = 0.0;
for (int j = id; j < N; j += NTHREADS) {
double item = (j % 2 == 1 ? 1 : -1) * 1.0 / (2 * j - 1);
sum += item;
}
return sum;
}));
}
double sum = 0.0;
for (Future<Double> future : futures) {
sum += future.get();
}
double pi = 4 * sum;
long end = System.currentTimeMillis();
System.out.println("Pi: " + pi);
System.out.println("Time: " + (end - start) + "ms");
executor.shutdown();
}
}
```
以上就是Java串行、并行、并发计算π的示例代码,希望能对您有所帮助。
阅读全文