package com.engine.htsc.doc.common;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Function 线程池操作类
 */
public class ThreadPoolUtil {
    private final static Logger logger = LoggerFactory.getLogger(ThreadPoolUtil.class);
    private static ExecutorService executorService = Executors.newCachedThreadPool();
    public static ConcurrentHashMap<String, String> hashMap_thread = new ConcurrentHashMap<>();

    /**
     * @Title: addTask
     * @Description: 新增线程任务
     * @Version 1.0
     * @Date 2016-12-12
     * @Author wangzk
     * @param asyncThread
     */
    public static void addTask(AsyncThread asyncThread){
        executorService.execute(asyncThread);
    }

    /**
     * @Title: addTask
     * @Description: 新增线程任务
     * @Version 1.0
     * @Date 2016-12-12
     * @Author wangzk
     * @param asyncThread
     */
    public static void addTask(AsyncThread asyncThread,String key){
        try {
            asyncThread.setKey(key);
            hashMap_thread.put(key, "0");
        } catch (Exception e) {
            logger.error("error happpens during add async task", e);
        }
        executorService.execute(asyncThread);
    }

    /**
     * @Title: addTask
     * @Description: 新增线程任务
     * @Version 1.0
     * @Date 2016-12-12
     * @Author wangzk
     * @param asyncThread
     */
    public static void addTask(Thread asyncThread){
        executorService.execute(asyncThread);
    }

    public static void addTask(Runnable task) {
        executorService.execute(task);
    }

    public static <T> T addCallableTask(Callable<T> task) {
        Future<T> future=executorService.submit(task);
        try {
            T result=future.get(2000, TimeUnit.MILLISECONDS);
            return result;
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            logger.error("执行线程过程中遇到问题",e);
            return null;
        }
    }

}