先了解了解线程
Java线程基础
线程池就是存储线程并管理线程的“池子”
new Thread的弊端如下:
a. 每次new Thread新建对象性能差。
b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new Thread,Java提供的四种线程池的好处在于:
a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、定期执行、单线程、并发数控制等功能。
线程池构造函数
//五个参数的构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
//六个参数的构造函数-1
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
//六个参数的构造函数-2
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler)
//七个参数的构造函数
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
corePoolSize -> 该线程池中核心线程数最大值
maximumPoolSize -> 该线程池中线程总数最大值
keepAliveTime -> 非核心线程闲置超时时长
BlockingQueue workQueue -> 线程池中的任务队列
ThreadFactory threadFactory -> 创建线程的工厂
RejectedExecutionHandler handler -> 饱和策略
系统也提供了封装好的线程池
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
使用:
ExecutorService threadPool = Executors.newSingleThreadExecutor(new NamedThreadFactory());
/**给你提供一种创建线程的策略,因为用了线程池之后,
*线程的创建都是由它内部自动创建的,但是有时候你可能想要对线程进行一些指定,
*比如是否守护线程,加入线程名,设置线程优先级等等,
*这个时候就可以用ThreadFactory来自己指定线程如何创建。*/
class NamedThreadFactory implements ThreadFactory {
private AtomicInteger tag = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("PictureSharpness:" + tag.getAndIncrement());
return thread;
}
}
什么情况下使用这类线程池?
看你需求,
需要一个常驻线程就用SingleThreadExecutor,
需要多个常驻线程就用FixedThreadPool,
不需要常驻线程就用CachedThreadPool,
当然也可以直接用ThreadPollExecutor。
更详细了解看这里
原子操作类AtomicInteger详解
一篇能够帮你理清线程池的文章
Android线程,线程池使用及原理博文参考
核心线程,非核心线程的区别你还记得吗?
Java(Android)线程池
线程池(5)-停止线程池里的任务









网友评论