一.线程池使用场景
二.线程池常用的几种方式
1.线程池的创建先来了解一下基本的构造参数
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
throw new RuntimeException("Stub!");}
corePoolSize: 线程池中核心线程数。
maximumPoolSize: 线程池中最大线程数。
keepAliveTime:非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收
unit:上面时间属性的单位
workQueue:线程池中的任务队列,通过线程池的
execute:方法提交的threadFactory:线程工厂,可用于设置线程名字等等,一般无须设置该参数。
2. Android中的四类线程池
2.1 FixThreadPool
FixThreadPool只有核心线程,且数量固定,不会被回收,线程都在执行时后面的任务会被等待
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());}public void excuteFixThreadPool()
{ ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); fixedThreadPool.execute(runnable);}2.2 SingleThreadPool
SingleThreadPool只有一个核心线程,所有任务都在同一线程中按顺序执行,先进先出
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory));}
public void excuteSingleThreadPool()
{ ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); singleThreadExecutor.execute(runnable);}
2.3 CachedThreadPool
CachedThreadPool没有核心线程,只有费核心线程,新任务会创建新线程,线程空闲超过指定时间会被回收,比较适合执行大量的耗时较少的任务。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());}
public void excuteCachedThreadPool()
{ ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); cachedThreadPool.execute(runnable);}
2.4 ScheduledThreadPool
从字面上看大概就知道是执行定时任务的线程管理,核心线程数固定,非核心线程(闲着没活干会被立即回收)数没有限制。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);}
public void excuteScheduledThreadPool ()
{ ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(runnable, 1, TimeUnit.SECONDS); //延迟1s后执行任务}