android 线程池封装,Android的线程和线程池

线程分为主线程和子线程,主线程主要处理和界面相关的事情,而子线程则往往用于执行耗时操作。

AsyncTask封装了线程池和Handler,它主要是为了方便开发者在子线程中更新UI。HandlerThread是一种具有消息循环的线程,在它的内部可以使用Handler。IntentService是一个服务,系统对其进行了封装使其可以更方便的执行后台任务,IntentService内部采用HandlerThread来执行任务,当任务执行完毕后IntentService会自动退出。从任务执行的角度来看,IntentService的作用很像一个后台进程,但是IntentService是一种服务,它不容易被系统杀死从而可以尽量保证任务的执行。

AsyncTask

AsyncTask是一种轻量级的异步任务类,它可以在线程池中执行后台任务,然后把执行的进度和最终结果传递给主线程并在主线程中更新UI。AsyncTask封装了Thread和Handler,但是并不是和进行特别耗时的后台任务。对于特别耗时的后台任务,推荐使用线程池。

AsyncTask是一个抽象的泛型类,它提供了Params、Progress和Resul这三个泛型参数,其中Params表示参数的类型,Progress表示后台任务的执行进度的类型,而Result则表示后台任务的返回结果的类型,如果AsyncTask缺失不需要传递具体的参数,那么这三个泛型参数都可以使用Void来代替。AsyncTask的声明如下。public abstract class AsyncTask

AsyncTask提供了4个核心方法:onPreExecute(),在主线程中执行,在异步任务执行之前,此方法会被调用,用于做准备工作。

doInBackground(Params... params),在线程池中执行,此方法用于执行异步任务,params参数表示异步任务的输入参数。在此方法中可以通过publishProgress方法来更新任务的进度,publishProgress方法会调用onProgressUpdate方法。另外此方法需要返回计算结果给onPostExecute方法。

onProgressUpdate(Progress... values),在主线程中执行,当后台任务的执行进度发生改变时此方法会被调用。

onPostExecute(Result result),在主线程中执行,在异步任务执行之后,此方法会被调用,其中result参数是后台任务的返回值,即doInBackground的返回值。

上面这几个方法,onPreExecute先执行,接着是doInBackground,最后是onPostExecute。除此之外还提供了onCancelled()方法,同样也是在主线程中调用,当异步任务被取消时,onCancelled()方法会被调用,此时onPostExecute不会被调用。public void onClick(View v) {    new DownloadImageTask().execute("http://example.com/image.png");

}private class DownloadImageTask extends AsyncTask {

/** The system calls this to perform work in a worker thread and

* delivers it the parameters given to AsyncTask.execute() */

protected Bitmap doInBackground(String... urls) {        return loadImageFromNetwork(urls[0]);

}    /** The system calls this to perform work in the UI thread and delivers

* the result from doInBackground() */

protected void onPostExecute(Bitmap result) {

mImageView.setImageBitmap(result);

}

}

AsyncTask在具体的使用过程中有如下需要注意的地方:AsyncTask的类必须在主线程中加载。

AsyncTask的对象必须在主线程中创建。

execute方法不惜在UI线程调用。

不要在程序中直接调用onPreExecute()、onPostExecute()、doInBackground 和 onProgressUpdate方法。

一个AsyncTask对象只能执行一次,即只能调用一次execute方法,否则会报运行时异常。

在Android1.6之前,AsyncTask是串行执行任务的,Android1.6的时候AsyncTask开始采用线程池处理并行任务,在Android3.0开始,为了避免AsyncTask所带来的并发错误,AsyncTask又采用一个线程来串行执行任务,但可以通过AsyncTask的executeOnExecutor方法来并行的执行任务。

HandlerThread

HandlerThread继承了Thread,它是一种可以使用Handler的Thread,它的实现是在run方法中通过Looper.prepare()来创建消息队列,并通过Looper.loop()来开启消息循环,这样在实际的使用中就允许在HandlerThread中创建Handler了。HandlerThread的run方法如下:public void run() {

mTid = Process.myTid();

Looper.prepare();        synchronized (this) {

mLooper = Looper.myLooper();

notifyAll();

}

Process.setThreadPriority(mPriority);

onLooperPrepared();

Looper.loop();

mTid = -1;

}

从HandlerThread的实现来看,它和普通的Thread有显著的不同之处。普通Thread主要用于在run方法中执行一个耗时任务,而HandlerThread在内部创建了消息队列,外界需要通过Handler的消息方式来通知HandlerThread执行一个具体的任务。由于HandlerThread的run方法是一个无限循环(loop是一个无限循环,run里面调用了Looper.loop(),所以run也是无限循环),因此当明确不需要再使用HandlerThread时,可以通过quit或者quitSafely方法来终止线程的执行。

IntentService

IntentService是一种特殊的Service,它继承了Service并且它是一个抽象类,因此必须创建它的子类才能使用IntentService。IntentService可用于执行后台耗时的任务,当任务执行后它会自动停止,同时由于IntentService是服务,优先级比单纯的线程要高很多,所以更适合执行一些高优先级的后台任务。在实现上,IntentService封装了HandlerThread和Handler,可以从onCreate方法中看出,如下:@Override

public void onCreate() {        // TODO: It would be nice to have an option to hold a partial wakelock

// during processing, and to have a static startService(Context, Intent)

// method that would launch the service & hand off a wakelock.

super.onCreate();

HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");

thread.start();

mServiceLooper = thread.getLooper();

mServiceHandler = new ServiceHandler(mServiceLooper);

}

当IntentService被第一次启动时,它的onCreate方法会被调用,onCreate方法会创建一个HandlerThread,然后使用它的Looper来构造一个Handler对象mServiceHandler,这样通过mServiceHandler发送的消息最终都会在HandlerThread中执行。IntentService是顺序执行后台任务的。在Android8.0及以上版本,建议使用JobIntentService。

官网上关于IntentService的说明

Android中的线程池

线程池的优点:重用线程池中的线程,避免弦音线程的创建和销毁所带来的性能开销。

能有效控制线程池的最大并发数,避免大量的线程之间因互相抢占系统资源而导致的阻塞现象。

能过对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。

Android中的线程池的概念来源于Java中的Executor,Executor是一个接口,真正的线程池的实现为ThreadPoolExecutor。 ThreadPoolExecutor提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程池,从线程池的功能特性来说,Android的线程池主要分为4类,这4类线程池可以通过Executors所提供的工厂方法来得到。

ThreadPoolExecutor是线程池的真正实现,它的构造方法提供了一系列参数来配置线程池。它提供了4个构造方法,以下面这个来说明各个参数的含义。public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,

TimeUnit unit,

BlockingQueue workQueue,

ThreadFactory threadFactory)

corePoolSize 线程池的核心线程数,默认情况下,核心线程会在线程池中一直存活,即使它们处于闲置状态。

maximumPoolSize线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞。

keepAliveTime非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收。当ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true时,keepAliveTime同样会作用于核心线程。

unit用于指定keepAliveTime参数的时间单位,是一个枚举,常用的有TimeUnit.MILLISECONDS、TimeUnit.SECONDS、TimeUnit.MINUTE等。

workQueue线程池中的任务队列,通过线程池的execute方法提交的Runable对象会存储在这个参数中。

threadFactory线程工厂,为线程池提供创建新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runable r)。

ThreadPoolExecutor执行任务时大致遵循如下规则:如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。

如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。

如果在步骤2中无法将任务插入到任务队列中,这往往死由于任务队列已满,这个时候如果线程数量未达到线程池规定的最大值,那么会立刻启动给一个非核心线程来执行任务。

如果步骤3中线程数量已经达到线程池规定的最大值,那么就拒绝执行任务,ThreadPoolExecutor会调用RejectedExecutionHandler的rejectedExecution方法来通知调用者。

常见的线程池

Android中最常见的四类具有不同功能特性的线程池,都直接或者间接的通过配置ThreadPoolExecutor来实现自己的功能特性。

FixedThreadPool 通过Executors的newFixedThredPool方法来创建。它是一种线程数量固定的线程池,当线程处于空闲状态时,它们并不会被回收,除非线程池被关闭了。当所有的线程都处于活动状态时,新任务都会处于等待状态,直到有线程空闲出来。由于FixedThreadPool只有核心线程并且这些核心线程不会被回收,这意味着它能够更加快速的响应外界的请求。/**

* Creates a thread pool that reuses a fixed number of threads

* operating off a shared unbounded queue.  At any point, at most

* {@code nThreads} threads will be active processing tasks.

* If additional tasks are submitted when all threads are active,

* they will wait in the queue until a thread is available.

* If any thread terminates due to a failure during execution

* prior to shutdown, a new one will take its place if needed to

* execute subsequent tasks.  The threads in the pool will exist

* until it is explicitly {@link ExecutorService#shutdown shutdown}.

*

* @param nThreads the number of threads in the pool

* @return the newly created thread pool

* @throws IllegalArgumentException if {@code nThreads <= 0}

*/

public static ExecutorService newFixedThreadPool(int nThreads) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue());

}

FixedThreadPool只有核心线程并且这些核心线程没有超时机制,另外任务队列也没有大小限制。

CachedThreadPool通过Executors的newCachedThreadPool方法来创建。它是一种线程数量不定的线程池,它只有非核心线程,并且其最大线程数为Integer.MAX_VALUE。由于

Integer.MAX_VALUE是一个很大的数,实际上就相当于最大线程数可以任意大。当线程池中的线程都处于活动状态时,线程池会创建新的线程来处理新任务,否则就会利用空闲的线程来处理新任务。线程池中的空闲线程都有超时机制,这个超时时长为60秒,超过60秒限制线程就会被回收,CachedThreadPool的任务队列相当于一个空集合,这将导致任何任务都会被立即执行,因为在这种场景下SyncchornousQueue是无法插入任务的。比较适合执行大量的耗时较少的任务。当整个线程池都处于闲置状态时,线程池中的线程都会超时而被停职,这个时候CachedThreadPool之中实际上是没有任何线程的,它几乎是不占任何系统资源的。/**

* Creates a thread pool that creates new threads as needed, but

* will reuse previously constructed threads when they are

* available.  These pools will typically improve the performance

* of programs that execute many short-lived asynchronous tasks.

* Calls to {@code execute} will reuse previously constructed

* threads if available. If no existing thread is available, a new

* thread will be created and added to the pool. Threads that have

* not been used for sixty seconds are terminated and removed from

* the cache. Thus, a pool that remains idle for long enough will

* not consume any resources. Note that pools with similar

* properties but different details (for example, timeout parameters)

* may be created using {@link ThreadPoolExecutor} constructors.

*

* @return the newly created thread pool

*/

public static ExecutorService newCachedThreadPool() {        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                      60L, TimeUnit.SECONDS,                                      new SynchronousQueue());

}

ScheduledThreadPool通过Executors的newScheduledThreadPool方法来创建。它的核心线程数量是固定的,而非核心线程数是没有限制的,并且当非核心线程闲置时会被立即回收。ScheduledThreadPool这类线程池主要用于执行定时任务和具有固定周期的重复任务。/**

* Creates a thread pool that can schedule commands to run after a

* given delay, or to execute periodically.

* @param corePoolSize the number of threads to keep in the pool,

* even if they are idle

* @return a newly created scheduled thread pool

* @throws IllegalArgumentException if {@code corePoolSize 

*/

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {        return new ScheduledThreadPoolExecutor(corePoolSize);

}

private static final long DEFAULT_KEEPALIVE_MILLIS = 10L;    /**

* Creates a new {@code ScheduledThreadPoolExecutor} with the

* given core pool size.

*

* @param corePoolSize the number of threads to keep in the pool, even

*        if they are idle, unless {@code allowCoreThreadTimeOut} is set

* @throws IllegalArgumentException if {@code corePoolSize 

*/

public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE,

DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,              new DelayedWorkQueue());

}

SingleThreadPool通过Executors的newSignleThreadExecutor方法来创建。这类线程池内部只有一个核心线程,它确保所有的任务都在同一个线程中按顺序执行。SingleThreadPool的意义在于统一所有的外界任务到一个线程中,这使得在这些任务之间不需要处理线程同步的问题。/**

* Creates an Executor that uses a single worker thread operating

* off an unbounded queue. (Note however that if this single

* thread terminates due to a failure during execution prior to

* shutdown, a new one will take its place if needed to execute

* subsequent tasks.)  Tasks are guaranteed to execute

* sequentially, and no more than one task will be active at any

* given time. Unlike the otherwise equivalent

* {@code newFixedThreadPool(1)} the returned executor is

* guaranteed not to be reconfigurable to use additional threads.

*

* @return the newly created single-threaded Executor

*/

public static ExecutorService newSingleThreadExecutor() {        return new FinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,                                    0L, TimeUnit.MILLISECONDS,                                    new LinkedBlockingQueue()));

}

作者:Tom_Ji

链接:https://www.jianshu.com/p/b2610e9592f0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值