Java8 并行计算

直接上代码吧,今天不想写太多文字

模拟延迟操作的接口
public interface RemoteLoader {

    String load();

    default void delay() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
实现类
CustomerInfoService 服务
package service;

/**
 * @author yuan_kf
 * @ClassName service.CustomerInfoService
 * @date 2021/1/28 09:25
 * @Description
 * @Version V1.0
 */

public class CustomerInfoService  implements RemoteLoader{
    @Override
    public String load()  {
        this.delay();
        return "基本信息";
    }
}

LabelService服务
package service;

/**
 * @author yuan_kf
 * @ClassName LabelService
 * @date 2021/1/28 09:43
 * @Description
 * @Version V1.0
 */

public class LabelService  implements RemoteLoader{
    @Override
    public String load() {
        this.delay();
        return "学习标签";
    }
}

LearnRecordService服务
package service;

/**
 * @author yuan_kf
 * @ClassName service.learnRecordService
 * @date 2021/1/28 09:26
 * @Description
 * @Version V1.0
 */

public class LearnRecordService implements RemoteLoader {
    @Override
    public String load() {
        this.delay();
        return "学习信息";
    }
}

WatchRecordService 服务
package service;

/**
 * @author yuan_kf
 * @ClassName WatchRecordService
 * @date 2021/1/28 09:44
 * @Description
 * @Version V1.0
 */

public class WatchRecordService implements RemoteLoader {
    @Override
    public String load() {
        this.delay();
        return "观看服务";
    }
}

测试类

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<RemoteLoader> remoteLoaderList = Arrays.asList(new CustomerInfoService(),new LearnRecordService());
        List<String> 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<RemoteLoader> remoteLoaders = Arrays.asList(new CustomerInfoService(), new LearnRecordService());

        List<Future<String>> futures = remoteLoaders.stream()
                .map(remoteLoader -> executorService.submit(remoteLoader::load))
                .collect(toList());

        List<String> 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<RemoteLoader> remoteLoaders = Arrays.asList(   new CustomerInfoService(),
                new LearnRecordService(),
                new LabelService(),
                new WatchRecordService());
        List<String> 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<String> 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<String> future = CompletableFuture.supplyAsync(() -> {
            doSomething();
            return "Finish";
        });
        System.out.println(future.get());
    }

    public static void testCompletableFuture3() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        List<RemoteLoader> remoteLoaders = Arrays.asList(
                new CustomerInfoService(),
                new LearnRecordService(),
                new LabelService(),
                new WatchRecordService());
        List<CompletableFuture<String>> completableFutures = remoteLoaders
                .stream()
                .map(loader -> CompletableFuture.supplyAsync(loader::load).exceptionally(throwable -> "Throwable exception message:" + throwable.getMessage()))
                .collect(toList());

        List<String> 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<RemoteLoader> remoteLoaders = Arrays.asList(
                new CustomerInfoService(),
                new LearnRecordService(),
                new LabelService(),
                new WatchRecordService());

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

        List<CompletableFuture<String>> completableFutures = remoteLoaders
                .stream()
                .map(loader -> CompletableFuture.supplyAsync(loader::load, executorService))
                .collect(toList());

        List<String> customerDetail = completableFutures
                .stream()
                .map(CompletableFuture::join)
                .collect(toList());

        System.out.println(customerDetail);
        long end = System.currentTimeMillis();
        System.out.println("总共花费时间:" + (end - start));
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值