• 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);


  • 相关阅读:
    Oracle BIEE整合百度图形库ECharts
    FineReport报表和J2EE应用的集成
    FusionChart对MDX查询结果的数据展示案例
    SharePoint 2013 配置开发环境,需安装VS2012插件
    SharePoint Online 创建门户网站系列之导航
    java实现简单的单点登录
    完整的Java简单浏览器
    Java实现全屏的四种方式(四个例子)
    在 Web 应用中实现全屏效果
    转载(原标题:网站再遭新威胁 Struts2又曝高危漏洞啦)
  • 原文地址:https://www.cnblogs.com/zgzf/p/10045374.html
Copyright © 2020-2023  润新知