ThreadUtils.java 1.99 KB
package com.ectrip.cyt.utils;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadUtils {
    private static ThreadPool instance;

    private ThreadUtils() {
    }

    public static ThreadPool getInstance() {
        if (instance == null) {
            synchronized (ThreadUtils.class) {
                if ((instance == null)) {
                    int cpuCount = Runtime.getRuntime().availableProcessors(); // 获取cpu数量,即核数
                    int threadCount = cpuCount * 2 + 1; //线程池中线程的个数---cpu核数*2+1--性能最佳
                    LogUtil.i("ThreadUtils", "ThreadUtils count == " + threadCount);
                    instance = new ThreadPool(threadCount, threadCount, 0L);

                }
            }
        }
        return instance;
    }

    public static class ThreadPool {
        private int corePoolSize;
        private int maximunPoolSize;
        private long keepAliveTime;

        private ThreadPoolExecutor executor;

        public ThreadPool(int corePoolSize, int maximunPoolSize, long keepAliveTime) {
            this.corePoolSize = corePoolSize;
            this.maximunPoolSize = maximunPoolSize;
            this.keepAliveTime = keepAliveTime;
        }

        public void exeute(Runnable runnable) {
            if (executor == null) {
                executor = new ThreadPoolExecutor(corePoolSize,
                        maximunPoolSize, keepAliveTime, TimeUnit.SECONDS,
                        new LinkedBlockingDeque<Runnable>(),
                        new ThreadPoolExecutor.AbortPolicy());

            }
            executor.execute(runnable);
        }

        public void cancel(Runnable r) {
            if (executor != null) {
                executor.getQueue().remove(r);
            }
        }

        public void close() {
            if (executor != null) {
                executor.shutdownNow();
            }
        }
    }
}