多线程执行工具方法

    public static <P, T> List<CompletableFuture<T>> multiThreadRun(Function<P, T> run, Collection<P> list, int threadSize, Executor executor, boolean waitRunFinal) {
        List<CompletableFuture<T>> cf = new ArrayList<>(threadSize);
        for (P obj : list) {
            cf.add(CompletableFuture.supplyAsync(() -> run.apply(obj), executor));
            if (waitRunFinal && cf.size() == threadSize) {
                cf.forEach(CompletableFuture::join);
                cf.clear();
            }
        }
        if(waitRunFinal) {
            cf.forEach(CompletableFuture::join);
        }
        return cf;
    }

 

posted @ 2023-08-30 18:04  数学与IT  阅读(79)  评论(0编辑  收藏  举报