其实我本人在Android 开发中,很少使用到线程池(AsyncTask 不算,虽然他是线程池+Handler 实现的),其实对于有大量的并发任务,线程池如何使用,还是要掌握的。线程池的优点可以概括为以下三点:
1,重用线程池中的线程,避免因为线程的创建和销毁所带来的性能开销。
2,能有效控制线程池的最大并发数,避免大量的线程之间因相互抢占系统资源而导致的阻塞现象
3,能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。
Android 中的线程池的概念来源于Java 中的Executor,Executor 是一个接口,真正的实现为ThreadPoolExecutor,他提供了一系列
参数来配置线程池,下面介绍ThreadPoolExecutor的构造方法。
/*
*@ ThreadPoolExecutor构造参数介绍
*
*/
public ThreadPoolExecutor(
//核心线程数,除非allowCoreThreadTimeOut被设置为true,否则它闲着也不会死
int corePoolSize,
//最大线程数,活动线程数量超过它,后续任务就会排队
int maximumPoolSize,
//超时时长,作用于非核心线程(allowCoreThreadTimeOut被设置为true时也会同时作用于核心线程),闲置超时便被回收
long keepAliveTime,
//枚举类型,设置keepAliveTime的单位,有TimeUnit.MILLISECONDS(ms)、TimeUnit. SECONDS(s)等
TimeUnit unit,
//缓冲任务队列,线程池的execute方法会将Runnable对象存储起来
BlockingQueue<Runnable> workQueue,
//线程工厂接口,只有一个new Thread(Runnable r)方法,可为线程池创建新线程
ThreadFactory threadFactory)
corePoolSize : 线程池的核心线程数,默认情况下,核心线程会在线程中一直存活,即使他们处于闲置状态。
maxmumPoolSize : 线程池所能容纳的最大线程数,当活动线程超过这个数值后,后续的新任务讲会被阻塞。
上面的注释已经写的很清楚了,下面讲讲线程池的分类:
1,FixedThreadPool
通过Executors的newFixedThreadPool 方法来创建,它是一种线程数量固定的线程池,当线程处于空闲状态时,他们并不会被回收,除非线程池关闭了。该线程池只有核心线程并且这些核心线程没有超时机制。
ExecutorService executorService = Executors.newFixedThreadPool(5);
executorService.execute(myTask);
Runnable myTask = new Runnable() {
@Override
public void run() {
Log.e(TAG,"MyRunnable == "+Thread.currentThread().getName());
/* try {
Thread.sleep(2000);
Log.e(TAG,"MyRunnable == "+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
};
2,CachedThreadPool
通过Executors 的newCachedTheadPool 来创建,它是一种数量不固定的线程池,她只有非核心线程,并且其最大线程数为Integer.MAX_VALUE 。
ExecutorService executorService = Executors.newCachedThreadPool();
//Executors.newFixedThreadPool(5);
executorService.execute(myTask);
3,SingleThreadExecutor
通过 Executors的newSingleThreadExecutor 来创建,这类线程池内部只有一个核心线程,它确保所有的任务都在同一个线程中按顺序执行。
super.onViewCreated(view, savedInstanceState);
ExecutorService executorService = Executors.newSingleThreadExecutor();
//Executors.newCachedThreadPool();
//Executors.newFixedThreadPool(5);
executorService.execute(myTask);
4,ScheduledThreadPool
通过 Executors 的 newScheduledTheadPool 来创建,主要用来执行定时任务和具有固定周期的重复任务。
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
// scheduledExecutorService.schedule(new MyRunnable(),2000, TimeUnit.MILLISECONDS);
scheduledExecutorService.scheduleAtFixedRate(myTask,2000,3000,TimeUnit.MILLISECONDS);
以上四种最好能自己实践,满足自己的需求为主。