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


  • 相关阅读:
    一文说透 Spring 循环依赖问题
    git修改已经push的commit message
    Connection Timeout 和CommandTimeout
    mvc 当中 [ValidateAntiForgeryToken] 的作用及用法
    mvc 当中 [ValidateAntiForgeryToken] 的作用及用法
    asp.net mvc与asp.net core Ajax删除操作delete中带ValidateAntiForgeryToken实例
    VS2017秘钥
    Sql server 2008 R2 配置管理工具服务显示远程过程调用失败:0x800706be
    SQL Server 2008找不到SQL Server配置管理器的问题
    如何为SQL Server2008添加登录账户并配置权限
  • 原文地址:https://www.cnblogs.com/zgzf/p/10045374.html
Copyright © 2020-2023  润新知