java并行计算收结果_Java8 并行计算

package demo;

import service.*;

import java.util.Arrays;

import java.util.List;

import java.util.Objects;

import java.util.concurrent.*;

import static java.util.stream.Collectors.toList;

/**

* @author yuan_kf

* @ClassName testSync

* @date 2021/1/28 09:27

* @Description

* @Version V1.0

*/

public class testSync {

public static void main(String[] args) throws ExecutionException, InterruptedException {

// sync();

// testFuture();

testParallelStream();

testCompletableFuture3();

testCompletableFuture4();

}

public static void sync(){

long start = System.currentTimeMillis();

List remoteLoaderList = Arrays.asList(new CustomerInfoService(),new LearnRecordService());

List customerDetail = remoteLoaderList.stream().map(RemoteLoader::load).collect(toList());

System.out.println(customerDetail);

long end = System.currentTimeMillis();

System.out.println("总共花费时间:" + (end - start));

}

public static void testFuture() {

long start = System.currentTimeMillis();

ExecutorService executorService = Executors.newFixedThreadPool(2);

List remoteLoaders = Arrays.asList(new CustomerInfoService(), new LearnRecordService());

List> futures = remoteLoaders.stream()

.map(remoteLoader -> executorService.submit(remoteLoader::load))

.collect(toList());

List customerDetail = futures.stream()

.map(future -> {

try {

return future.get();

} catch (InterruptedException | ExecutionException e) {

e.printStackTrace();

}

return null;

})

.filter(Objects::nonNull)

.collect(toList());

System.out.println(customerDetail);

long end = System.currentTimeMillis();

System.out.println("总共花费时间:" + (end - start));

}

public static void testParallelStream() {

long start = System.currentTimeMillis();

List remoteLoaders = Arrays.asList( new CustomerInfoService(),

new LearnRecordService(),

new LabelService(),

new WatchRecordService());

List customerDetail = remoteLoaders.parallelStream().map(RemoteLoader::load).collect(toList());

System.out.println(customerDetail);

long end = System.currentTimeMillis();

System.out.println("总共花费时间:" + (end - start));

}

public void testCompletableFuture() {

CompletableFuture future = new CompletableFuture<>();

new Thread(() -> {

try {

doSomething();

future.complete("Finish");

} catch (Exception e) {

future.completeExceptionally(e);

} //任务执行完成后 设置返回的结果

}).start();

System.out.println(future.join()); //获取任务线程返回的结果

}

private void doSomething() {

System.out.println("doSomething...");

}

public void testCompletableFuture2() throws ExecutionException, InterruptedException {

CompletableFuture future = CompletableFuture.supplyAsync(() -> {

doSomething();

return "Finish";

});

System.out.println(future.get());

}

public static void testCompletableFuture3() throws ExecutionException, InterruptedException {

long start = System.currentTimeMillis();

List remoteLoaders = Arrays.asList(

new CustomerInfoService(),

new LearnRecordService(),

new LabelService(),

new WatchRecordService());

List> completableFutures = remoteLoaders

.stream()

.map(loader -> CompletableFuture.supplyAsync(loader::load).exceptionally(throwable -> "Throwable exception message:" + throwable.getMessage()))

.collect(toList());

List customerDetail = completableFutures

.stream()

.map(CompletableFuture::join)

.collect(toList());

System.out.println(customerDetail);

long end = System.currentTimeMillis();

System.out.println("总共花费时间:" + (end - start));

}

public static void testCompletableFuture4() throws ExecutionException, InterruptedException {

long start = System.currentTimeMillis();

List remoteLoaders = Arrays.asList(

new CustomerInfoService(),

new LearnRecordService(),

new LabelService(),

new WatchRecordService());

ExecutorService executorService = Executors.newFixedThreadPool(Math.min(remoteLoaders.size(), 50));

List> completableFutures = remoteLoaders

.stream()

.map(loader -> CompletableFuture.supplyAsync(loader::load, executorService))

.collect(toList());

List customerDetail = completableFutures

.stream()

.map(CompletableFuture::join)

.collect(toList());

System.out.println(customerDetail);

long end = System.currentTimeMillis();

System.out.println("总共花费时间:" + (end - start));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于求π的并行实现,我可以提供以下思路: 1. 划分任务:将π的计算任务划分为多个子任务,每个子任务计算一部分π的值。 2. 分配任务:将子任务分配给不同的线程或进程并发执行。 3. 同步结果:等待所有线程或进程执行完毕后,将它们计算出的π的值合并起来得到最终结果。 以下是一种基于Java的并行实现: ``` import java.util.concurrent.*; public class ParallelPi { public static void main(String[] args) throws InterruptedException, ExecutionException { int numThreads = 4; // 设定线程数 int numSteps = 100000000; // 计算π的步数 double step = 1.0 / numSteps; // 步长 ExecutorService executor = Executors.newFixedThreadPool(numThreads); // 创建线程池 Future<Double>[] futures = new Future[numThreads]; // 创建Future数组 for (int i = 0; i < numThreads; i++) { int start = i * numSteps / numThreads; int end = (i + 1) * numSteps / numThreads; Callable<Double> task = new PiCalculator(start, end, step); // 创建任务 futures[i] = executor.submit(task); // 提交任务 } double sum = 0.0; for (int i = 0; i < numThreads; i++) { sum += futures[i].get(); // 合并结果 } double pi = step * sum * 4.0; System.out.println("π ≈ " + pi); executor.shutdown(); // 关闭线程池 } } class PiCalculator implements Callable<Double> { private final int start; private final int end; private final double step; public PiCalculator(int start, int end, double step) { this.start = start; this.end = end; this.step = step; } @Override public Double call() throws Exception { double sum = 0.0; for (int i = start; i < end; i++) { double x = (i + 0.5) * step; sum += 1.0 / (1.0 + x * x); } return sum; } } ``` 以上代码中,我们使用了Java的Executor框架,将π的计算任务划分为多个子任务,并发执行,最后将结果合并得到最终的π值。此外,为了提高计算精度,我们使用了莱布尼茨级数公式计算π的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值