自定义线程池管理类
16lz
2021-01-25
import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadFactory;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;public class ThreadPoolManager { private static ThreadPoolManager mInstance; private int corePoolSize; /** * 最大线程池数量,表示当缓冲队列满的时候能继续容纳的等待任务的数量 */ private int maximumPoolSize; /** * 存活时间 */ private long keepAliveTime = 1; private TimeUnit unit = TimeUnit.HOURS; private ThreadPoolExecutor executor; // 缓冲队列 private static BlockingQueue workQueue = null; public static ThreadPoolManager getInstance() { if (mInstance == null){ synchronized (ThreadPoolManager.class){ if (mInstance == null){ mInstance = new ThreadPoolManager(); mInstance.init(); } } } return mInstance; } private void init(){ //给corePoolSize赋值:当前设备可用处理器核心数*2 + 1,能够让cpu的效率得到最大程度执行(有研究论证的) corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1; maximumPoolSize = corePoolSize; workQueue = new LinkedBlockingQueue(100); executor = new ThreadPoolExecutor( //当某个核心任务执行完毕,会依次从缓冲队列中取出等待任务 corePoolSize, //5,先corePoolSize,然后new LinkedBlockingQueue(),然后maximumPoolSize,但是它的数量是包含了corePoolSize的 maximumPoolSize, //表示的是maximumPoolSize当中等待任务的存活时间 keepAliveTime, unit, //缓冲队列,用于存放等待任务,Linked的先进先出// new LinkedBlockingQueue(), workQueue, //创建线程的工厂 // Executors.defaultThreadFactory(), new DefaultThreadFactory(Thread.NORM_PRIORITY, "tiaoba-pool-"), //用来对超出maximumPoolSize的任务的处理策略 new ThreadPoolExecutor.AbortPolicy() ); } private static class DefaultThreadFactory implements ThreadFactory { /** * 线程池的计数 */ private static final AtomicInteger poolNumber = new AtomicInteger(1); /** * 线程的计数 */ private final AtomicInteger threadNumber = new AtomicInteger(1); private final ThreadGroup group; private final String namePrefix; private final int threadPriority; DefaultThreadFactory(int threadPriority, String threadNamePrefix) { this.threadPriority = threadPriority; //默认线程组 this.group = Thread.currentThread().getThreadGroup(); namePrefix = threadNamePrefix + poolNumber.getAndIncrement() + "-thread-"; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); //isDaemon() 测试该线程是否为守护线程 if (t.isDaemon()) { t.setDaemon(false); } t.setPriority(threadPriority); return t; } } public void execute(Runnable runnable) { if (executor == null){ init(); } if (runnable != null){ executor.execute(runnable); } }}
更多相关文章
- Android(安卓)Json解析
- contentProvider不是线程安全的
- Android线程间通信
- 阿里、腾讯、百度、网易、美团Android面试经验分享,拿到了百度、
- 2020年GitHub标星2.9K的Android基础——高级面试题合集!(金九银十
- android杀不死的Service
- android开发之widget控件突然停止更新的原因
- Android开发规范之编码规范
- 2018-6月Android试题整理