William

不管走了多远都不要忘记为什么出发

0%

Android 中的线程和线程池

Android 中的线程和线程池

我们知道线程是CPU调度的最小单位。在Android中主线程是不能够做耗时操作的,子线程是不能够更新UI的。在Android中,除了Thread外,扮演线程的角色有很多,如AsyncTask,IntentService和HandlerThread等等。良好的线程使用习惯有助于减少 app 出现崩溃和性能开销的风险,接下来介绍一下线程池的使用。

线程池的好处

不知道大家有没有遇到过这种情况。我们在写项目,遇到耗时操作的时候,怎么办呢,是不是new Thread().start,那这样的话,整个项目中得new多少个Thread。这种明显是很浪费性能。那么有没有一种可以方法对线程进行复用呢?答案就是线程池。

先说一下线程池的好处:

  • 重用线程池中的线程,避免因为线程的创建和销毁带来的性能开销。
  • 能有效的控制线程池中的线程并发数,避免大量线程之间因为互相抢占资源而导致的阻塞现象。
  • 能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。

ThreadPoolExecutor

Android中的线程池概念是来源于java中ExecutorExecutor是一个空的接口,真正的线程池实现ThreadPoolExecutor

1
2
3
4
5
6
7
8
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler);
}

简单介绍一下ThreadPoolExcutor各个参数的含义:

  • corePoolSize:线程池的核心线程数,默认情况下,核心线程会在线程池中一直存活,即使他们处于闲置状态。当我们把ThreadPoolExecutor中的allowCoreThreadTimeOut属性设置为true,那么闲置的核心线程在等待新任务的时候,如果时间超过keepAliveTime所设置的时间,核心线程将会被回收。

    1
    2
    private volatile long keepAliveTime;
    private volatile boolean allowCoreThreadTimeOut;
  • maximumPoolSize:设置最大线程池能够容纳的最大线程数,当线程池中的线程达到这个数以后,新任务将会被阻塞。

  • keepAliveTime:非核心线程数闲置的时间。

  • unit:指定keepAliveTime参数的时间单位。

  • workQueue:线程池中的任务队列。

  • threadFactory:线程工厂,为线程池提供创建新线程的功能。

  • handler:该handler的类型为RejectedExecutionHandler。这个参数不常用,它的作用是当线程池无法执行新任务时,会调用handlerrejectedExecution(Runnable r, ThreadPoolExecutor e)方法来抛出异常。无法执行的原因可能是由于队列满或者任务无法成功执行等。

ThreadPoolExecutor执行任务大致遵循以下规则:

  1. 如果线程池中的线程数量未达到核心线程的数量,会直接启动一个核心线程来执行任务。
  2. 如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。
  3. 如果第2步中无法插入新任务,说明任务队列已满,如果未达到规定的最大线程数量,则启动一个非核心线程来执行任务。
  4. 如果第3步中线程数量超过规定的最大值,则拒绝任务并使用RejectedExecutionHandlerrejectedExecution(Runnable r, ThreadPoolExecutor e)方法来通知调用者。

线程池的分类

Android中常见的线程池有四种,FixedThreadPoolCachedThreadPoolScheduledThreadPoolSingleThreadExecutor

FixedThreadPool(Fixed:固定的,不变的)

FixedThreadPool线程池是通过Executorsnew FixedThreadPool方法来创建。它的特点是该线程池中的线程数量是固定的。即使线程处于闲置的状态,它们也不会被回收,除非线程池被关闭。当所有的线程都处于活跃状态的时候,新任务就处于队列中等待线程来处理。注意,FixedThreadPool只有核心线程,没有非核心线程。总结如下:

  • 线程数量固定且都是核心线程:核心线程数量和最大线程数量都是nThreads;
  • 都是核心线程且不会被回收,快速相应外界请求;
  • 没有超时机制,任务队列也没有大小限制;
  • 新任务使用核心线程处理,如果没有空闲的核心线程,则排队等待执行。
1
2
3
4
5
6
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}

CachedThreadPool(Cached:缓存)

CachedThreadPool线程池是通过Executorsnew CachedThreadPool进行创建的。它是一种线程数目不固定的线程池,它没有核心线程,只有非核心线程,当线程池中的线程都处于活跃状态,就会创建新的线程来处理新的任务。否则就会利用闲置的线程来处理新的任务。线程池中的线程都有超时机制,这个超时机制时长是60s,超过这个时间,闲置的线程就会被回收。这种线程池适合处理大量并且耗时较少的任务。这里得说一下,CachedThreadPool的任务队列,基本都是空的。总结如下:

  • 线程数量不定,只有非核心线程,最大线程数任意大:传入核心线程数量的参数为0,最大线程数为Integer.MAX_VALUE
  • 有新任务时使用空闲线程执行,没有空闲线程则创建新的线程来处理。
  • 该线程池的每个空闲线程都有超时机制,时常为60s(参数:60L, TimeUnit.SECONDS),空闲超过60s则回收空闲线程。
  • 适合执行大量的耗时较少的任务,当所有线程闲置超过60s都会被停止,所以这时几乎不占用系统资源。
1
2
3
4
5
 public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}

ScheduledThreadPool(Scheduled:预定的、排定的)

ScheduledThreadPool线程池是通过Executorsnew ScheduledThreadPool进行创建的,它的核心线程是固定的,但是非核心线程数是不固定的,并且当非核心线程一处于空闲状态,就立即被回收。这种线程适合执行定时任务和具有固定周期的重复任务。总结如下:

  • 核心线程数量固定,非核心线程数量无限制;
  • 非核心线程闲置超过10s会被回收;
  • 主要用于执行定时任务和具有固定周期的重复任务;
  • 四个里面唯一一个有延时执行和周期重复执行的功能:创建时
    ScheduledThreadPoolExecutor(corePoolSize)返回的是new ScheduledThreadPoolExecutor对象,ScheduledThreadPoolExecutorThreadPoolExecutor的子类,DelayedWorkQueueScheduledThreadPoolExecutor的一个静态内部类,主要用于处理任务队列延迟的工作。
1
2
3
4
5
6
7
8
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
// 默认闲置超时回收时常
private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS, new DelayedWorkQueue());
}

SingleThreadExecutor(单线程线程池)

SingleThreadExecutor线程池是通过Executorsnew SingleThreadExecutor方法来创建的,这类线程池中只有一个核心线程,也没有非核心线程,这就确保了所有任务能够在同一个线程并且按照顺序来执行,这样就不需要考虑线程同步的问题。总结如下:

  • 只有一个核心线程,所有任务在同一个线程按顺序执行。
  • 所有的外界任务统一到一个线程中,所以不需要处理线程同步的问题。
1
2
3
4
5
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runable>()));
}

Android线程池简单使用

上面所说的四种常用线程池的实例化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 创建一个Runnable对象
Runnable runnable = new Runnable() {
@Override
public void run() {
// do something
}
};
// 四种线程池执行Runnable对象
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);
fixedThreadPool.execute(runnable);

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(runnable);

// 注意这里创建的是ScheduledExecutorService对象,ScheduledExecutorService是ExecutorService的子类
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
// 1000ms后执行runnable
scheduledThreadPool.schedule(runnable,1000,TimeUnit.MILLISECONDS);
// 1000ms后,每3000ms执行一次runnable
scheduledThreadPool.scheduleAtFixedRate(runnable,1000,2000,TimeUnit.MILLISECONDS);
isRunning = true;

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(runnable);

简单使用demo

添加线程池开始执行和ScheduledThreadPool停止执行的两个按钮点击事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count = 0;
mStatueText.setText("线程开始执行,次数:"+ count);
startThreadPool();
}
});
findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(null != scheduledThreadPool && isRunning){
scheduledThreadPool.shutdown();
mStatueText.setText("scheduledThreadPool线程停止,当前次数:"+ count);
isRunning = false;
}
}
});

startThreadPool();方法里Runnable每执行一次增加一次count并打到TextView上:

1
2
3
4
5
6
7
8
9
10
11
12
Runnable runnable = new Runnable() {
@Override
public void run() {
count++;
runOnUiThread(new Runnable() {
@Override
public void run() {
mStatueText.setText("线程执行完毕,次数:"+ count);
}
});
}
};

接着让所有的线程池执行这个Runnable对象,最后的结果是变量count的值从0直接到了3,然后又到5最后无限增长。
原因是除ScheduledThreadPool对象外的三个线程池很快执行了任务,ScheduledThreadPool对象的执行了两次任务,两个都延时1000ms。最后循环执行的任务一直在增加count的值。

如果对你有帮助,欢迎赞赏。