一:使用线程池的原因
在android开发中经常会使用多线程异步来处理相关任务,而如果用传统的newThread来创建一个子线程进行处理,会造成一些严重的问题:
1:在任务众多的情况下,系统要为每一个任务创建一个线程,而任务执行完毕后会销毁每一个线程,所以会造成线程频繁地创建与销毁。
2:多个线程频繁地创建会占用大量的资源,并且在资源竞争的时候就容易出现问题,同时这么多的线程缺乏一个统一的管理,容易造成界面的卡顿。
3:多个线程频繁地销毁,会频繁地调用GC机制,这会使性能降低,又非常耗时。
总而言之:频繁地为每一个任务创建一个线程,缺乏统一管理,降低性能,并且容易出现问题。
为了解决这些问题,就要用到今天的主角——线程池.
线程池使用的好处:
1:对多个线程进行统一地管理,避免资源竞争中出现的问题。
2:(重点):对线程进行复用,线程在执行完任务后不会立刻销毁,而会等待另外的任务,这样就不会频繁地创建、销毁线程和调用GC。
3:JAVA提供了一套完整的ExecutorService线程池创建的api,可创建多种功能不一的线程池,使用起来很方便。
二:几种常见的线程池
ThreadPoolExecutor 创建基本线程池
创建线程池,主要是利用ThreadPoolExecutor这个类,而这个类有几种构造方法,其中参数最多的一种构造方法如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
1、newSingleThreadExecutor的使用
public class ThreadExecutorUtils {
private static final String TAG = "ThreadExecutorUtils";
private ExecutorService singleThreadExecutor;
private static volatile ThreadExecutorUtils mThreadExecutorUtils;
private ThreadExecutorUtils() {
//创建Single线程池
singleThreadExecutor = Executors.newSingleThreadExecutor();
}
public static ThreadExecutorUtils getInstance() {
if (mThreadExecutorUtils == null) {
synchronized (ThreadExecutorUtils.class) {
if (mThreadExecutorUtils == null) {
mThreadExecutorUtils = new ThreadExecutorUtils();
}
}
}
return mThreadExecutorUtils;
}
/**
* SingleThreadPool(单个核线的fixed)
*/
public void singleThreadExecutor(){
for(int i = 0;i<5;i++){
final int finali = i;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
Log.d(TAG, "run: "+finali);
Log.d("当前线程:",Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
singleThreadExecutor.execute(runnable);
}
}
}
结果:每2s打印一个任务,由于只有一个核心线程,当被占用时,其他的任务需要进入队列等待。
参考文章:https://www.jianshu.com/p/7b2da1d94b42