美文网首页程序员
【Android】线程和线程池

【Android】线程和线程池

作者: renkuo | 来源:发表于2018-09-14 19:35 被阅读14次

    子曰:“温故而知新,可以为师矣。我们都是站在巨人的肩膀上一点点的前进,最近翻翻以前看的书,决定整理一下读书笔记,希望对一些人会有帮助。
    言归正传,我们一起进入正题。除了Thread 本身以外,在Android中可以扮演线程角色的还有很多,比如AsyncTask和IntentService,同时HandlerThread也是种特殊的线程。 尽管AsyncTask、IntentService以及HandlerThread的表现形式和传统的线程不同, 但是它们的本质仍然是传统的线程。 对于AsyncTask来说, 它的底层用到线程池,它用到了两个线程池,一个是给任务排队,另一个是真的的去执行任务。对于IntentService和HandlerThread来说,它们底层直接使用了线程。
    在操作系统中,线程是操作系统调度的最小单元,同时线程又是 种受限的系统资源,即线程不可能无限制地产生, 并且线程的创建和销毁都会有相应的开销。 当系统中存在大量的线程时, 系统会通过时间片轮转的方式调度每个线程, 因此线程不可能做到绝对的并行, 除非线程数量小手等于CPU的核心数,一般来说这是不可能的。试想一下, 如果在一个进程中频繁地创建和销毁线程, 这显然不是高效的做法。 正确的做法是采用钱程池,线程池会缓存一定数量的线程,通过线程池可以避免因为频繁的创建和销毁线程所带来的开销。
    Android中主要分为主线程和子线程,主线程也就是UI线程。主线程主要处理界面的交互逻辑以及运行四大组件,不能执行耗时操作。这个时候我们就把所有的耗时操作都交给子线程,比如网络请求,I/O操作等。

    AsyncTask

    AsyncTask封装了线程池和Handler,它主要是为了方便开发者在子线程中更UI。AsyncTask属于比较轻量的异步任务类,它并不适合进行特别耗时的后台任务。特别耗时的任务建议直接使用线程池。
    AsyncTask是一个抽象泛型类,它有三个泛型参数。分别是Params,Progress,Result。
    a.Params表示参数的类型
    b.Progress表示后台任务执行的进度类型
    c.Result表示后台任务的返回结果类型。

    AsyncTask的四个核心方法

    1.onPreExecute(),主线程中执行,在异步任务执行之前,一般用于做一些准备工作

    /**
         * Runs on the UI thread before {@link #doInBackground}.
         * @see #onPostExecute
         * @see #doInBackground
         */
        @MainThread
        protected void onPreExecute() {
        }
    

    2.doInBackground(Params... params)在线程池中执行,用于执行异步任务。此方法可以通过publishProgress方法进行更新进度,publishProgress会调用OnProgressUdat方法,另外该方法需要返回计算结果给onPostExecute方法

        /**
         * Override this method to perform a computation on a background thread. The
         * specified parameters are the parameters passed to {@link #execute}
         * by the caller of this task.
         * This method can call {@link #publishProgress} to publish updates
         * on the UI thread.
         * @param params The parameters of the task.
         * @return A result, defined by the subclass of this task.
    
         */
        @WorkerThread
        protected abstract Result doInBackground(Params... params);
    

    3.onProgressUpdate(Progress... values)在主线程中执行,后台任务执行进度发生改变时,此方法会被调用(例如下载文件进度实现)

        /**
         * Runs on the UI thread after {@link #publishProgress} is invoked.
         * The specified values are the values passed to {@link #publishProgress}.
         * @param values The values indicating progress.
         */
        @SuppressWarnings({"UnusedDeclaration"})
        @MainThread
        protected void onProgressUpdate(Progress... values) {
        }
    

    4.onPostExecute(Result result)在主线程中执行,在异步任务执行之后执行,result代表返回值

    /**
         * <p>Runs on the UI thread after {@link #doInBackground}. The
         * specified result is the value returned by {@link #doInBackground}.</p>
         * <p>This method won't be invoked if the task was cancelled.</p>
         * @param result The result of the operation computed by {@link #doInBackground}.
         */
        @SuppressWarnings({"UnusedDeclaration"})
        @MainThread
        protected void onPostExecute(Result result) {
        }
    

    注:使用过程中注意通过isCancelled()方法,判断任务是否被取消,一般可以在doInBackground中做。另外需要注意:1.AsyncTask的对象必须在主线程中创建。2.执行任务调用execute方法,必须在UI线程调用。3.不要在程序中直接调用AsyncTask的那四个核心方法。4.一个AsyncTask只能执行一次,也就是说只能调用一次execute方法。5.Android3.0以后AsyncTask都是串行运行的
    至于为什么AsyncTask要在主线程加载?相信大家也会有疑问。
    由于AsyncTask会通过handler发送一个消息,为了能过将执行的环境切换到主线程,就要求这个handler对象必须在主线程创建,因此变相的要求AsyncTask必须在主线程加载

    HandlerThread

    普通Thread主要是在run方法中执行一个耗时任务,而HandlerThread是在它的内部创建了一个消息队列,外部需要通过Handler的消息方式来通知HandlerThread去执行任务。HanlderThread的run方法是一个无限循环,因此当我们不需要用到它的时候,可以通过quit或quitSafely方法来终止线程。HandlerThread的run方法源码如下:

        @Override
        public void run() {
            mTid = Process.myTid();
            Looper.prepare();
            synchronized (this) {
                mLooper = Looper.myLooper();
                notifyAll();
            }
            Process.setThreadPriority(mPriority);
            onLooperPrepared();
            Looper.loop();
            mTid = -1;
        }
    

    IntentService

    IntentService是一种特殊的Service,它是继承Service的一个抽象类,我们要使用IntentService必须创建IntentService的子类。IntentService内部使用HandlerThread来执行任务,当任务执行完毕的时候IntentService会自动退出。IntentService很像是一个后台的线程,但是由于它是服务,所以不容易被系统杀死,能保证任务的执行。如果是一个后台线程,这个时候进程中没有四大组件活动,那么这个线程的优先级就会变得非常低,从而很容易被系统杀死。IntentService封装了HandlerThread和Handler,我们从它的源码中就可以分析出来,

        @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对象。我们知道每次启动服务,它的onStartCommand方法都会被调用。在IntentService中,onStartCommand方法会处理外界的Intent,然后调用onStart方法,

        /**
         * You should not override this method for your IntentService. Instead,
         * override {@link #onHandleIntent}, which the system calls when the IntentService
         * receives a start request.
         * @see android.app.Service#onStartCommand
         */
        @Override
        public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
            onStart(intent, startId);
            return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
        }
    
       @Override
        public void onStart(@Nullable Intent intent, int startId) {
            Message msg = mServiceHandler.obtainMessage();
            msg.arg1 = startId;
            msg.obj = intent;
            mServiceHandler.sendMessage(msg);
        }
    

    可以看出IntentService是通过handler发送消息,然后这个消息有HandlerThread处理,handler收到消息以后,会通过onHandlerIntent方法处理Intent。onHandlerIntent方法执行以后,IntentService会尝试通过stopSelf(int startId)方法来停止服务。为什么不使用stopself()方法呢?因为stopself()方法会立刻停止服务,这样可能导致其它消息未被处理。ServiceHandler实现如下:

        private final class ServiceHandler extends Handler {
            public ServiceHandler(Looper looper) {
                super(looper);
            }
    
            @Override
            public void handleMessage(Message msg) {
                onHandleIntent((Intent)msg.obj);
                stopSelf(msg.arg1);
            }
        }
    

    onHandlerIntent方法是一个抽象方法,它要在子类中实现,它的作用是根据Intent参数来区分要执行的任务。如果目前只有一个后台任务, 那么onHandlelntent方法执行完这个任务后, stopSelf(intstartld)就会直接停止服务;如果目前存在多个后台任务,那么onHandleintent方法执行完最后一个任务是停止服务。使用IntentService执行任务的时候要求每执行一个任务就要启动一次IntentService,由于IntentService内部实现是Handler,意味着IntentService执行任务也是顺序执行后台任务的。调用方式如下:

    Intent service = new Intent(this, MinelntentService.class);
    service.putExtra("action","com.renkuo.example.action.ONE");
    startService(service);
    service.putExtra("action","com.renkuo.example.action.TWO");
    startService(service);
    service.putExtra("action","com.renkuo.example.action.Three");
    startService(service);
    

    线程池

    线程池的好处

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

    ThreadPoolExecutor

    ThreadPoolExecutor是真正的线程池的实现,ThreadPoolExecutor的一个很常用的构造方法

        /**
         * Creates a new {@code ThreadPoolExecutor} with the given initial
         * parameters and default rejected execution handler.
         *
         * @param corePoolSize the number of threads to keep in the pool, even
         *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
         * @param maximumPoolSize the maximum number of threads to allow in the
         *        pool
         * @param keepAliveTime when the number of threads is greater than
         *        the core, this is the maximum time that excess idle threads
         *        will wait for new tasks before terminating.
         * @param unit the time unit for the {@code keepAliveTime} argument
         * @param workQueue the queue to use for holding tasks before they are
         *        executed.  This queue will hold only the {@code Runnable}
         *        tasks submitted by the {@code execute} method.
         * @param threadFactory the factory to use when the executor
         *        creates a new thread
         * @throws IllegalArgumentException if one of the following holds:<br>
         *         {@code corePoolSize < 0}<br>
         *         {@code keepAliveTime < 0}<br>
         *         {@code maximumPoolSize <= 0}<br>
         *         {@code maximumPoolSize < corePoolSize}
         * @throws NullPointerException if {@code workQueue}
         *         or {@code threadFactory} is null
         */
        public ThreadPoolExecutor(int corePoolSize,
                                  int maximumPoolSize,
                                  long keepAliveTime,
                                  TimeUnit unit,
                                  BlockingQueue<Runnable> workQueue,
                                  ThreadFactory threadFactory) {
            this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
                 threadFactory, defaultHandler);
        }
    

    ThreadPoolExecutor参数含义:
    1.corePoolSize:线程池的核心线程数,默认情况下,核心线程会在线程池中一直存活, 即使它们处于闲置状态。如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true时,那么闲置的核心线程在等待新任务到来时会有超时策略, 这个时间间隔由keepAliveTime所指定, 当等待时间超过keepAliveTime所指定的时长后, 核心线程会被终止。
    2.maximumPoolSize:线程池所能容纳的最大线程数,当活动线程数达到这个数值后, 后续的新任务将会被阻塞。
    3.keepAliveTime:非核心线程闲置时的超时 时长,超过这个时长,非核心线程就会被回收。当ThreadPool­Executor的allowCoreThreadTimeOut属性设置为true 时,keepAliveTime同样会作用于核心线程。
    4.unit:时于指定keepAliveTime 参数的时间单位, 这是一个枚举。
    5.workQueue:线程池中的任务队列,通过线程池的execute方法 提交的Runnable对象会存储在这个参数中。
    6.threadFactory:线程工厂, 为线程池提供创建新线程的功能。 ThreadFactory是一个接口,它只有一个方法Thread newThread(Runnable r)。
    除了这几个参数以外,还有一个RejectedExceptionHandler handler。这个参数基本用不到,一个很不常用的参数。当线程池无法执行新任务时,这可能是由于任务队列己满或者是无法成功执行任务, 这个时候ThreadPoolExecutor会调用handler 的rejectedExecution方法来通知调用者, 默认情况下rejectedExecution方法会直接抛出 个RejectedExecution­Exception 。 ThreadPoolExecutor为RejectedExecutionHandler提供了几个可选值:CallerRunsPolicy、 AbortPolicy、 DiscardPolicy和DiscardOldestPolicy, 其中AbortPolicy是 默认值, 它会直接抛出RejectedExecutionException 。

    ThreadPoolExecutor执行任务时有以下几条规则:

    1.如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。
    2.如果线程池中的线程数量己经达到或者越过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。
    3.如果在步骤2中无法将任务插入到任务队列中,这往往是由于任务队列己满,这个时候如果线程数量未达到线程地规定的最大值, 那么会立刻启动一个非核心线程来执行任务任务。
    4.如果步骤3中线程数量已经达到线程池规定的最大值, 那么就拒绝执行此任务, ThreadPoolExecutor会调用RejectedExecutionHandler的rectedExecution方法来通知调用者。

    如何配置一个线程池

    通过一些android源码(AsyncTask源码)发现配置后的线程池规格如下:

    • 核心线程数量为CPU的核心数+1
    • 线程池的最大线程数为CPU的核心数*2 + 1
    • 核心线程无超时机制,非核心线程的闲置时超时时间为1秒
    • 任务队列容量为128
    常用的线程池

    FixedThreadPool,CachedThreadPool,ScheduledThreadPool,SingleThreadExecutor

    FixedThreadPool

    通过Executors的newFixedThreadPool方法创建。 这是一种线程数量固定的线程池。当线程处于空闲状态时, 它们并不会被回收, 除非线程池被关闭了。 当所有的线程都处于活动状态时, 新任务会处于等待状态, 直到有线程空闲出来。 由于FixedThreadPool只有核心线程并且这些核心线程不会被回收,这意味着它能够更加快速地响应外界的请求。 newFixedThreadPool方法的实现如下, 可以发现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<Runnable>());
        }
    
    CachedThreadPool

    通过Executors的newCachedThreadPool方法创建。它只有非核心线程池,并且最大线程数为Integer.MAX_VALUE,实际相当于线程数可以无限大。当线程池中的线程都处于活跃状态的时候,线程池就会创建新的线程来执行新的任务,反之有未处于活跃状态的线程时,用空闲线程执行新任务。线程池的空闲线程都有超时机制,超时时间为60秒,超过60秒就会回收。和FixedThreadPool 不同的是CachedThreadPool的任务队列其实相飞于一个空集合, 这将导致任何任务都会立即被执行, 因为在这种场景下SynchronousQueue是无法插入任务。SynchronousQueue是一个非常特殊的队列,很多情况下可以把它简单的理解为一个无法存储元素的队列。 从 CachedThreadPool的特性来看, 这类线程池比较适合执行大量的耗时较少的任务。当整个线程池都处于闲置状态时,线程池中的线程部会超时而被停止,这个时候CachedThreadPool 之巾实际上是没有任何线程的, 它几于是不占用任何系统资源的。 newCachedThreadPool

        /**
         * 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<Runnable>());
        }
    
    ScheduledThreadPool

    通过Executors的newScheduledThreadPool方法创建。 它的核心线程数量是固定的,而非核心线程数是int的最大值, 并且当非核心线程闲置时会被立即回收。 ScheduledThreadPool 这类线程池主要用于执行定时任务和具有固定周期的重复任务, newScheduledThreadPool方法的实现如下所示。

        /**
         * 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 < 0}
         */
        public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
            return new ScheduledThreadPoolExecutor(corePoolSize);
        }
    
        /**
         * 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 < 0}
         */
        public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE,
                  DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
                  new DelayedWorkQueue());
        }
    
    SingleThreadExecutor

    通过Executors的 newSingleThreadExecutor方法创建。 这类线程池内部只有一个核心线程,它能够确保所有的任务都在同一个线程中按顺序执行。它的意义在于统一所有的任务在一个线程中执行,是的这些任务不再需要考虑同步的问题。

         * 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<Runnable>()));
        }
    

    错误不足之处或相关建议欢迎大家评论指出,谢谢!如果觉得内容可以的话麻烦喜欢(♥)一下

    相关文章

      网友评论

        本文标题:【Android】线程和线程池

        本文链接:https://www.haomeiwen.com/subject/movogftx.html