一种是使用Executors工厂生产线程池;另一种是直接使用ThreadPoolExecutor自定义。
Executors工厂生产线程池
Java(Android)线程池
Trinea
介绍new Thread的弊端及Java四种线程池的使用,对Android同样适用。本文是基础篇,后面会分享下线程池一些高级功能。
1、new Thread的弊端
执行一个异步任务你还只是如下new Thread吗?
Java
1 2 3 4 5 6 7 |
newThread(newRunnable(){ @Override publicvoidrun(){ // TODO Auto-generated method stub } }).start(); |
那你就out太多了,new Thread的弊端如下:
a. 每次new Thread新建对象性能差。
b. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom。
c. 缺乏更多功能,如定时执行、定期执行、线程中断。
相比new Thread,Java提供的四种线程池的好处在于:
a. 重用存在的线程,减少对象创建、消亡的开销,性能佳。
b. 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞。
c. 提供定时执行、定期执行、单线程、并发数控制等功能。
2、Java 线程池
Executors工厂类:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html
Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package.
ExecutorService接口:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
All Known Implementing Classes: AbstractExecutorService, ForkJoinPool, ScheduledThreadPoolExecutor, ThreadPoolExecutor
Java通过Executors提供四种线程池(主要使用Executors工厂方式生产线程池),分别为:
newCachedThreadPool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
(1). newCachedThreadPool
创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ExecutorService cachedThreadPool=Executors.newCachedThreadPool(); for(inti=0;i<10;i++){ finalintindex=i; try{ Thread.sleep(index*1000); }catch(InterruptedExceptione){ e.printStackTrace(); } cachedThreadPool.execute(newRunnable(){ @Override publicvoidrun(){ System.out.println(index); } }); } |
线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。
(2). newFixedThreadPool
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ExecutorService fixedThreadPool=Executors.newFixedThreadPool(3); for(inti=0;i<10;i++){ finalintindex=i; fixedThreadPool.execute(newRunnable(){ @Override publicvoidrun(){ try{ System.out.println(index); Thread.sleep(2000); }catch(InterruptedExceptione){ // TODO Auto-generated catch block e.printStackTrace(); } } }); } |
因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。可参考PreloadDataCache。
(3) newScheduledThreadPool
创建一个定长线程池,支持定时及周期性任务执行。
延迟执行示例代码如下:
Java
1 2 3 4 5 6 7 8 |
ScheduledExecutorService scheduledThreadPool=Executors.newScheduledThreadPool(5); scheduledThreadPool.schedule(newRunnable(){ @Override publicvoidrun(){ System.out.println("delay 3 seconds"); } },3,TimeUnit.SECONDS); |
表示延迟3秒执行。
定期执行示例代码如下:
Java
1 2 3 4 5 6 7 |
scheduledThreadPool.scheduleAtFixedRate(newRunnable(){ @Override publicvoidrun(){ System.out.println("delay 1 seconds, and excute every 3 seconds"); } },1,3,TimeUnit.SECONDS); |
表示延迟1秒后每3秒执行一次。
ScheduledExecutorService比Timer更安全,功能更强大,后面会有一篇单独进行对比。
(4)、newSingleThreadExecutor
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
ExecutorService singleThreadExecutor=Executors.newSingleThreadExecutor(); for(inti=0;i<10;i++){ finalintindex=i; singleThreadExecutor.execute(newRunnable(){ @Override publicvoidrun(){ try{ System.out.println(index); Thread.sleep(2000); }catch(InterruptedExceptione){ // TODO Auto-generated catch block e.printStackTrace(); } } }); } |
结果依次输出,相当于顺序执行各个任务。
现行大多数GUI程序都是单线程的。Android中单线程可用于数据库操作,文件操作,应用批量安装,应用批量删除等不适合并发但可能IO阻塞性及影响UI线程响应的操作。
来源: http://www.trinea.cn/android/java-android-thread-pool/
JAVA的Executors源码:(可以看出底层都是通过ThreadPoolExecutor来具体设置的~)
publicstaticExecutorServiceMore...newCachedThreadPool(){
returnnewThreadPoolExecutor(0,Integer.MAX_VALUE,
60L,TimeUnit.SECONDS,
newSynchronousQueue<Runnable>());
}
publicstaticExecutorServiceMore...newFixedThreadPool(int nThreads){
returnnewThreadPoolExecutor(nThreads, nThreads,
0L,TimeUnit.MILLISECONDS,
newLinkedBlockingQueue<Runnable>());
}
publicstaticExecutorServiceMore...newSingleThreadExecutor(ThreadFactory threadFactory){
returnnewFinalizableDelegatedExecutorService
(newThreadPoolExecutor(1,1,
0L,TimeUnit.MILLISECONDS,
newLinkedBlockingQueue<Runnable>(),
threadFactory));
}
publicstaticScheduledExecutorServiceMore...newScheduledThreadPool(int corePoolSize){
returnnewScheduledThreadPoolExecutor(corePoolSize);
}
(ScheduledThreadPoolExecutor :extends ThreadPoolExecutor , implements ScheduledExecutorService)
ThreadPoolExecutor自定义
以上是一些JAVA封装现成设置后得到的线程池,更灵活的自定义设置:
ThreadPoolExecutor:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
BlockingQueue接口:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
ThreadFactory接口: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadFactory.html
RejectedExecutionHandler:http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RejectedExecutionHandler.html
ThreadPoolExecutor提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程池:
1.corePoolSize
:核心线程数,默认情况下,核心线程会在线程中一直存活;
2.maximumPoolSize
:最大线程数,当活动线程数达到这个数值后,后续的任务将会被阻塞;
3.keepAliveTime
:非核心线程闲置时的超时时长,超过这个时长,闲置的非核心线程就会被回收;
4.unit
:用于指定keepAliveTime参数的时间单位,有TimeUnit.MILLISECONDS
、TimeUnit.SECONDS
、TimeUnit.MINUTES
等;
5.workQueue
:任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中;
6.threadFactory
:线程工厂,为线程池提供创建新线程的功能。它是一个接口,它只有一个方法Thread newThread(Runnable r)
;
7.RejectedExecutionHandler
:当线程池无法执行新任务时,可能是由于任务队列已满或者是无法成功执行任务,这个时候就会调用这个Handler的rejectedExecution
方法来通知调用者,默认情况下,rejectedExecution
会直接抛出个rejectedExecutionException
。
ThreadPoolExecutor执行任务的规则:
1.如果线程池中的线程数未达到核心线程的数量,那么会直接启动一个核心线程来执行任务;
2.如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行;
3.如果在步骤2中无法将任务插入到的任务队列中,可能是任务队列已满,这个时候如果线程数量没有达到规定的最大值,那么会立刻启动非核心线程来执行这个任务;
4.如果步骤3中线程数量已经达到线程池规定的最大值,那么就拒绝执行此任务,ThreadPoolExecutor会调用RejectedExecutionHandler
的rejectedExecution
方法来通知调用者。
使用示例:
public final classThreadUtils{
privatestatic final String TAG =ThreadUtils.class.getSimpleName();
publicstaticThreadPoolExecutor newCachedThreadPool(final String name){
returnnewThreadPoolExecutor(0,Integer.MAX_VALUE,
60L,TimeUnit.SECONDS,
newSynchronousQueue<Runnable>(),
newCounterThreadFactory(name),
newLogDiscardPolicy());
}
publicstaticThreadPoolExecutor newFixedThreadPool(final String name,int nThreads){
returnnewThreadPoolExecutor(nThreads, nThreads,
0L,TimeUnit.MILLISECONDS,
newLinkedBlockingQueue<Runnable>(),
newCounterThreadFactory(name),
newLogDiscardPolicy());
}
publicstaticThreadPoolExecutor newSingleThreadExecutor(final String name){
return newFixedThreadPool(name,1);
}
publicstaticclassLogDiscardPolicy implements RejectedExecutionHandler{
publicLogDiscardPolicy(){
}
publicvoid rejectedExecution(Runnable r,ThreadPoolExecutor e){
LogUtils.v(TAG,"rejectedExecution() "+ r +" is discard.");
}
}
publicstaticclassCounterThreadFactory implements ThreadFactory{
privateint count;
privateString name;
publicCounterThreadFactory(String name){
this.name =(name == null ?"Android": name);
}
@Override
publicThread newThread(Runnable r){
Thread thread =newThread(r);
thread.setName(name +"-thread #"+ count++);
return thread;
}
}
}