package com.imdroid.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class ThreadManager {

    //单线程池
    private static final Map<String, ExecutorService> mExecutorServiceMap = new HashMap<>();
    private static final Object lock = new Object();

    private static final class FixedThreadPoolHolder {
        //固定线程池
        static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
    }

    public static ExecutorService getFixedThreadPool() {
        return FixedThreadPoolHolder.fixedThreadPool;
    }

    private static final class ScheduledThreadPoolHolder {
        //定时线程池
        static final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);
    }

    public static ScheduledExecutorService getScheduledThreadPool() {
        return ScheduledThreadPoolHolder.scheduledThreadPool;
    }


    public static ExecutorService getSingleThreadPool(String name) {
        ExecutorService singleThreadExecutor = mExecutorServiceMap.get(name);
        if (singleThreadExecutor == null) {
            synchronized (lock) {
                singleThreadExecutor = mExecutorServiceMap.get(name);
                if (singleThreadExecutor == null) {
                    singleThreadExecutor = Executors.newSingleThreadExecutor();
                    mExecutorServiceMap.put(name, singleThreadExecutor);
                }
            }
        }
        return singleThreadExecutor;
    }
}
