ThreadPoolExecutor 主要有以下几个参数:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
复制代码
参数说明
corePoolSize 核心线程数量
- 即使没有任务执行,核心线程也会一直存活
- 线程数小于核心线程时,即使有空闲线程,线程沲也会创建新线程执行任务
- 设置allowCoreThreadTimeout=true时,核心线程会超时关闭
maximumPoolSize 最大线程数
- 当所有核心线程都在执行任务,且任务队列已满时,线程沲会创建新线程执行任务
- 当线程数=maxPoolSize,且任务队列已满,此时添加任务时会触发RejectedExecutionHandler进行处理
keepAliveTime TimeUnit 线程空闲时间
- 如果线程数>corePoolSize,且有线程空闲时间达到keepAliveTime时,线程会销毁,直到线程数量=corePoolSize
- 如果设置allowCoreThreadTimeout=true时,核心线程执行完任务也会销毁直到数量=0
workQueue 任务队列
- ArrayBlockingQueue 有界队列,需要指定队列大小
- LinkedBlockingQueue 若指定大小则和ArrayBlockingQueue类似,若不指定大小则默认能存储Integer.MAX_VALUE个任务,相当于无界队列,此时maximumPoolSize值其实是无意义的
- SynchronousQueue 同步阻塞队列,当有任务添加进来后,必须有线程从队列中取出,当前线程才会被释放,newCachedThreadPool就使用这种队列
ThreadFactory 创建线程的工厂
- 通过他可以创建线程时做一些想做的事,比如自定义线程名称:
private static class CustomThreadFactory implements ThreadFactory {
private final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
CustomThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
namePrefix = "ume-pool-" + POOL_NUMBER.getAndIncrement() + "-thread-";
}
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = new Thread(group, runnable, namePrefix + threadNumber.getAndIncrement(), 0);
if (thread.isDaemon()) {
thread.setDaemon(false);
}
if (thread.getPriority() != Thread.NORM_PRIORITY) {
thread.setPriority(Thread.NORM_PRIORITY);
}
return thread;
}
}
复制代码
RejectedExecutionHandler 线程数和队列都满的情况下,对新添加的任务的处理方式
- AbortPolicy 直接抛出异常
- CallerRunsPolicy 直接调用新添加runnable.run函数执行任务
- DiscardPolicy 直接抛弃任务,什么也不干
- DiscardOldestPolicy 抛弃队列中最先加入的任务,然后再添加新任务
下面是自定义实现,相当于DiscardPolicy,只打印异常信息
private static class CustomRejectedExecutionHandler implements RejectedExecutionHandler {
private CustomRejectedExecutionHandler() {
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
Log.e("umeweb", "Task " + r.toString() + " rejected from " + e.toString());
}
}
复制代码
附上一个自己在用的简单线程沲实现
private final ThreadPoolExecutor mExecutor;
private ThreadPoolManager() {
final int cpu = Runtime.getRuntime().availableProcessors();
final int corePoolSize = cpu + 1;
final int maximumPoolSize = cpu * 2 + 1;
final long keepAliveTime = 1L;
final TimeUnit timeUnit = TimeUnit.SECONDS;
final int maxQueueNum = 128;
mExecutor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
timeUnit,
new LinkedBlockingQueue<Runnable>(maxQueueNum),
new CustomThreadFactory(),
new CustomRejectedExecutionHandler());
}
public void executor(@NonNull Runnable runnable) {
mExecutor.execute(runnable);
}
复制代码