package com.tzld.piaoquan.recommend.server.framework.utils;


import java.util.concurrent.*;

/**
 * 命名线程池工场类
 * 最后创建的线程名称:
 *   name_{counter}
 */
class NamedThreadFactory implements ThreadFactory {
    private int counter = 0;
    private String name;
    NamedThreadFactory(String name) {
        this.name = name;
    }

    @Override
    public Thread newThread(Runnable r) {
        counter += 1;
        return new Thread(r, name + "_" + counter);
    }
}


public class ThreadPoolUtils {
    public static ThreadPoolExecutor newFixedThreadPool(int nThreads, String poolName) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("Fixed_" + poolName));
    }
    public static ThreadPoolExecutor newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
    }

    public static ThreadPoolExecutor newCachedThreadPool(String poolName) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>(), new NamedThreadFactory("Cached_" + poolName));
    }

    public static ThreadPoolExecutor newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
    }
}

