java多线程分批调用接口

线程池工具类

public class ThreadPoolUtil {

    public static final long DEFAULT_WAIT_SECONDS = 5000;

    private static class ThreadPool {
        private static final ThreadFactory namedThreadFactory =
            new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build();
        private static final ThreadPoolExecutor pool = new ThreadPoolExecutor(20, 40, 60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(200), namedThreadFactory, new ThreadPoolExecutor.DiscardPolicy()) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                printException(r, t);
            }
        };
    }

    /**
     * 获取线程池.
     */
    public static ExecutorService getThreadPool() {
        log.info("ThreadPool task num now: {}", ThreadPool.pool.getActiveCount());
        return ThreadPool.pool;
    }

    private static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>)r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt(); // ignore/reset
            }
        }
        if (t != null) {
            log.error(t.getMessage(), t);
        }
    }

    /**
     * 使用线程池并发执行任务.
     *
     * @param callables
     *            任务列表
     *
     * @param waitSeconds
     *            等待时间(秒)
     *
     * @return.
     */
    public static <T> List<T> executeTasks(List<Callable<T>> callables, long waitSeconds) {
        return doExecute(callables, waitSeconds, ThreadPool.pool);
    }

    private static <T> List<T> doExecute(List<Callable<T>> callables, long waitSeconds, ThreadPoolExecutor executor) {
        try {
            List<T> result = Lists.newArrayList();
            if (callables == null || callables.isEmpty()) {
                return result;
            }
            List<Future<T>> futures = executor.invokeAll(callables);
            try {
                for (Future<T> future : futures) {
                    result.add(future.get(waitSeconds, TimeUnit.SECONDS));
                }
            } catch (Exception e) {
                throw e;
            } finally {
                for (Future<T> future : futures) {
                    try {
                        future.cancel(true);
                    } catch (Exception e2) {
                    }
                }
            }
            return result;
        } catch (Exception e) {
            log.error("doExecute error", e);
            throw new RuntimeException(e.getMessage());
        }
    }
}

使用Callable

public String getTableOwnersByTableGuid(List<String> tableGuids) {
        String ret = "[";
        List<Callable<String>> callables = Lists.newArrayList();
        tableGuids.stream().forEach(tableGuid -> {
            Callable<String> callable = () -> Optional.ofNullable(odpsTableManager.queryOdpsTableBaseInfo(tableGuid)).map(
                GetMetaTableBasicInfoResponse.Data::getOwnerId).orElse(null);
            callables.add(callable);
        });
        List<String> ownerIdList = ThreadPoolUtil.executeTasks(callables, ThreadPoolUtil.DEFAULT_WAIT_SECONDS).stream().filter(
            Objects::nonNull).collect(Collectors.toList());
        for (String ownerId : ownerIdList) {
            ret += "'" + ownerId + "',";
        }
        return StringUtils.stripEnd(ret, ",") + "]";
    }

使用CompletableFuture

public String getTableOwnersByTableGuid1(List<String> tableGuids) {
        String ret = "[";
        List<CompletableFuture<String>> completableFutureList = Lists.newArrayList();
        tableGuids.stream().forEach(tableGuid -> {
            try {
                CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> odpsTableManager.queryOdpsTableBaseInfo(tableGuid).getOwnerId());
                completableFutureList.add(future);
            } catch (Exception e) {
                log.info("getTableOwnersByWorkOrderId queryOdpsTableBaseInfo fail");
            }
        });
        List<String> ownerIdList = completableFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
        for (String ownerId : ownerIdList) {
            ret += "'" + ownerId + "',";
        }
        return StringUtils.stripEnd(ret, ",") + "]";
    }

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值