自定义线程池管理类

ThreadFactoryImpl

/**
 * @description 自定义ThreadFactory,可以自己组装线程名
 */
public class ThreadFactoryImpl implements ThreadFactory {
    /**
     * 线程池数
     */
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    /**
     * 线程数
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    ThreadFactoryImpl(String prefix, String suffix) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = prefix + poolNumber.getAndIncrement() + suffix;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            //判断是否为守护线程
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

ThreadPoolMannager

/**
 * @description 线程池管理类
 */
public class ThreadPoolManager {
    private volatile static ThreadPoolManager threadPoolManager = null;

    private int corePoolSize;
    /**
     * 最大线程池数量,表示当缓冲队列满的时候能继续容纳的等待任务的数量
     */
    private int maximumPoolSize;
    /**
     * 存活时间
     */
    private long keepAliveTime = 10;
    private TimeUnit unit = TimeUnit.MINUTES;
    private String prefix = "pool-";
    private String suffix = "-Thread-";
    private ThreadPoolExecutor executor;
    // 缓冲队列【阻塞式队列】
    private static BlockingQueue workQueue = null;

    public static void main(String[] args) {
        ThreadPoolManager threadPoolManager = ThreadPoolManager.getThreadPoolManager();
        ThreadPoolExecutor executor = threadPoolManager.getExecutor();
        System.out.println("核心线程数+" + executor.getCorePoolSize());
        System.out.println("最大线程数+" + executor.getMaximumPoolSize());
        for (int i = 0; i < 20; i++) {
            executor.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println("活跃+" + executor.getActiveCount());
        System.out.println("总线程数+" + executor.getPoolSize());
        System.out.println("进行任务数+" + executor.getTaskCount());
        System.out.println("完成任务数+" + executor.getCompletedTaskCount());
    }

    private ThreadPoolManager() {
    }

    public ThreadPoolExecutor getExecutor() {
        return executor;
    }

    public static ThreadPoolManager getThreadPoolManager() {
        if (threadPoolManager == null) {
            synchronized (ThreadPoolManager.class) {
                if (threadPoolManager == null) {
                    threadPoolManager = new ThreadPoolManager();
                    threadPoolManager.init();
                }
            }
        }
        return threadPoolManager;
    }

    private void init() {
        //给corePoolSize赋值:当前设备可用处理器核心数*2 + 1,能够让cpu的效率得到最大程度执行(有研究论证的)
        corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
        maximumPoolSize = corePoolSize;
        workQueue = new LinkedBlockingQueue(100);
        //创建自定义fixed线程池
        executor = new ThreadPoolExecutor(
                //当某个核心任务执行完毕,会依次从缓冲队列中取出等待任务
                corePoolSize,
                //5,先corePoolSize,然后new LinkedBlockingQueue(),然后maximumPoolSize,但是它的数量是包含了corePoolSize的
                maximumPoolSize,
                //表示的是maximumPoolSize当中等待任务的存活时间,一段时间没有任务就消亡
                keepAliveTime,
                unit,
                //缓冲队列,用于存放等待任务,Linked的先进先出
                //new LinkedBlockingQueue(),
                workQueue,
                //创建线程的工厂
                //  Executors.defaultThreadFactory(),
                new ThreadFactoryImpl(prefix, suffix),
                //用来对超出maximumPoolSize的任务的处理策略
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    /**
     * 执行任务
     */
    public void execute(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        executor.execute(runnable);
    }

    /**
     * 从线程池中移除任务
     */
    public void remove(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        executor.remove(runnable);
    }

    private void test() {
        /**
         * 只有一个核心线程,确保所有任务都在同一线程中按顺序完成。
         * 因此不需要处理线程同步的问题。
         */
        Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
        /**
         * 只有核心线程,并且数量固定的,也不会被回收,
         * 所有线程都活动时,因为队列没有限制大小[Integer.MAX_VALUE],新任务会等待执行。
         */
        Executors.newFixedThreadPool(1, Executors.defaultThreadFactory());
        /**
         * CachedThreadPool只有非核心线程,最大线程数非常大,所有线程都活动时,
         * 会为新任务创建新线程,否则利用空闲线程(60s空闲时间,过了就会被回收,
         * 所以线程池中有0个线程的可能)处理任务。
         */
        Executors.newCachedThreadPool(Executors.defaultThreadFactory());
        /**
         * (4个里面唯一一个有延迟执行和周期重复执行的线程池),ScheduledThreadPool主要用于执行定时任务以及有固定周期的重复任务。
         */
        Executors.newScheduledThreadPool(1, Executors.defaultThreadFactory());
    }

}

你可能感兴趣的:(java系列)