zoukankan      html  css  js  c++  java
  • Java异步、线程池解决方案

    一、ThreadPoolExecutor------线程池
    private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(30, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(60), new ThreadPoolExecutor.AbortPolicy());
    static {
            threadPoolExecutor.allowCoreThreadTimeOut(true);
        }
    System.out.println("======start=======");
    threadPoolExecutor.execute(() -> {
                System.out.println("=============");
            });
    System.out.println("=========end========");

    //异步执行操作

    参考资料:https://blog.csdn.net/qq_25806863/article/details/71126867

    二、CompletableFuture----获取结果

    CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> {C
        System.out.println("==========2=========");
        return 1;
    });
    CompletableFuture<Integer> res = CompletableFuture.supplyAsync(() -> {
        return 2;
    });

    Integer x = result.get();
    Integer y = res.get();
    三、异步工具类
    public interface AsyncToolCommon {
        /**
         * 异步执行一个无参无返回值的方法
         * @param voidFunction
         * @throws Exception
         */
        void asyncFunction(VoidFunction voidFunction);
    
        /**
         * 异步执行一个无参有返回值的方法
         * @param supplier
         */
        <T> void asyncSupplier(Supplier<T> supplier);
    }
    @Service
    public class AsyncToolCommonImpl implements AsyncToolCommon {
        private static final Logger logger = LoggerFactory.getLogger(AsyncToolCommonImpl.class);
    
        private static final ForkJoinPool forkJoinPool = new ForkJoinPool(2 * Runtime.getRuntime().availableProcessors() + 1);
    
        /**
         * 异步执行一个无参无返回值的方法
         *
         * @param voidFunction
         * @throws Exception
         */
        @Override
        public void asyncFunction(VoidFunction voidFunction) {
            CompletableFuture.supplyAsync(() -> {
                try {
                    voidFunction.execute();
                    return ResultEnum.SUCCESS.getCode();
                } catch (Exception e) {
                    logger.error("asyncExecute error:{}", e);
                    throw new RuntimeException(e);
                }
            }, forkJoinPool);
        }
    
        /**
         * 异步执行一个无参有返回值的方法
         *
         * @param supplier
         */
        @Override
        public <T> void asyncSupplier(Supplier<T> supplier) {
            CompletableFuture.supplyAsync(() -> supplier.get(), forkJoinPool);
        }
    
    }
    @FunctionalInterface
    public interface VoidFunction {
        /**
         * 无参构造体
         */
        void execute() throws Exception;
    }
    asyncToolCommon.asyncFunction(() -> .....);

    四、循环调用

    List<CompletableFuture<Integer>> futureList = Lists.newArrayList();
    for(int i=0;i<10;i++){
    futureList.add(CompletableFuture.supplyAsync(() -> {C
        System.out.println("==========2=========");
        return 1;
    });)
    }
    int count = 0;
    for (CompletableFuture<Integer> future : futureList) {
           Integer i = future.get(600, TimeUnit.MILLISECONDS);
           count += i;
    }

    五、Fork/Join
    //线程池
    private ForkJoinPool facePlatFormForkJoinPool = new ForkJoinPool(20);
    private ForkJoinPool faceInfoForkJoinPool = new ForkJoinPool(20);
    Callable<SearchResultJson> facePlatformCallable = () -> faceService.search(img, searchReq.getClientName(), searchReq.getClientIp(), finalAppSecret, finalToken);
    //回调执行结果
    Future<SearchResultJson> facePlatFormFuture =facePlatFormForkJoinPool.submit(facePlatformCallable);
    SearchResultJson facePlatFormResp = facePlatFormFuture.get(6000, TimeUnit.MILLISECONDS);
    
    Callable<Response<FaceInfoResult>> faceInfoCallable = () -> faceJsfService.getFaceInfo(faceInfoParam);
    Future<Response<FaceInfoResult>> faceInfoFuture = faceInfoForkJoinPool.submit(faceInfoCallable);
    Response<FaceInfoResult> faceInfoResp = faceInfoFuture.get(6000, TimeUnit.MILLISECONDS);


  • 相关阅读:
    OpenYurt v0.4.0 新特性发布:高效地管理边缘存储资源
    OpenKruise v0.9.0 版本发布:新增 Pod 重启、删除防护等重磅功能
    dubbo-go v3 版本 go module 踩坑记
    阿里云携手 VMware 共建云原生 IoT 生态,聚开源社区合力打造领域标准
    一文告诉你Java日期时间API到底有多烂
    LocalDateTime、OffsetDateTime、ZonedDateTime互转,这一篇绝对喂饱你
    全球城市ZoneId和UTC时间偏移量的最全对照表
    全网最全!彻底弄透Java处理GMT/UTC日期时间
    GMT UTC CST ISO 夏令时 时间戳,都是些什么鬼?
    如何保证Redis高可用和高并发
  • 原文地址:https://www.cnblogs.com/zgzf/p/10045374.html
Copyright © 2011-2022 走看看