package com.zksy.common.utils;


import com.zksy.common.config.ThreadPoolConfig;
import lombok.Getter;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.function.Supplier;

/**
 * 需要传一个泛型代表返回结果result的类型
 * @param <K>
 */
public class ThreadPoolRunTaskListUtil <K> {
    private final ThreadPoolConfig poolConfig;
    private final ArrayList<Callable<K>> needBeExecutedList = new ArrayList<>();
    @Getter
    private Collection<K> result = null;
    @SafeVarargs
    public ThreadPoolRunTaskListUtil (ThreadPoolConfig poolConfig, Callable<K> ... callableResultList){
        this.poolConfig = poolConfig;
        needBeExecutedList.addAll(Arrays.asList(callableResultList));
    }
    public ThreadPoolRunTaskListUtil runTaskList(Supplier<Collection<K>> contianer){
        List<Future<K>> futures = new ArrayList<>();
        needBeExecutedList.forEach(task -> {
            futures.add(poolConfig.threadPoolTaskExecutor().submit(task));
        });
        Collection<K> ks = contianer.get();
        for (Future<K> future : futures) {
            try {
                K result = future.get();
                ks.add(result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        this.result = ks;
        return this;
    }
    public Vector<K> getResultVector() {
        return (Vector<K>) this.result;
    }

}

