Android 中线程和线程池

来源:互联网 发布:高校网络教育阳光招生服务平台 编辑:程序博客网 时间:2024/05/21 10:55

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

Android中线程池概念来源于java中的Executor,Executor是一个接口,真正实现为TheradPoolExecutor,他提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程池,由于android 中的线程池都是由ThreadPoolExecutor来实现的,首先介绍ThreadPoolExecutor

这个是ThreadPoolExecutor的构造,分析一下

  public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue,                              ThreadFactory threadFactory) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             threadFactory, defaultHandler);    }

corePoolSize :
线程池核心线程数,默认情况下,核心线程会在线程池一直存活,即使他们处于闲置状态,如果将ThreadPoolExecutor的allowCoreThreadTimeOut设为true。那么闲置的可信线程等待新任务到来时回事超时策略,这个时间由KeepAliveTime所指定,当等待时间超过KeepAliveTime时长时候,和细心线程就会终止

maximumPoolSize:
线程池能容纳多少线程数,当活动线程数达到这个数值后,后续的任务将会被阻塞

KeepAliveTime
非核心线程闲置超时时长,超过这个时间,非核心线程就会被回收

unit
用于指定KeepAliveTime 参数的时间单位,这是一个枚举常有的(TimeUtils。SECONDS 秒)

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

ThreadFactory
线程工厂,为线程池提供创建新线程的功能

ThreadPoolExector执行任务大致遵循以下规则
(1)如果线程池中线程数量未达到核心线程数,那么会直接启动一个核心线程来执行任务
(2)如果线程池中线程数量已经超过和细心线程的数量那么任务会插入到任务列表中排队等待执行
(3)如果在步骤二中无法插入,往往是由于任务队列已满,这个时候如果线程数量达到未达到线程池规定的最大值,那么会直接启动一个非核心线程来执行任务
(4)如果步骤三线程数量以及几个达到线程池规定的最大值,那么就拒绝执行此任务,会调用ThreadPoolExecutor的RejectedExecutionHandler方法通知调用者

ThreadPoolExtecutor参数配置,在AscyncTask中有明显的体现,

//核心线程最大为4最小为2 private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)); //线程池最大线程数cup的2倍加1 private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; //超时时间30s private static final int KEEP_ALIVE_SECONDS = 30; //任务队列容量128   private static final BlockingQueue<Runnable> sPoolWorkQueue =            new LinkedBlockingQueue<Runnable>(128);

线程池的分类

1 FixedThreadPool
通过 Executors的newFixedThreadPool方法来创建,他是一个线程数固定的线程池,当线程处于空下线状态时,他们并不会被回收,除非线程池被关闭,当所有的线程处于活动状态时,新任务都会处于等待状态,知道有线程空闲出来,由于FixedThreadPool只有核心线程数并且这些不会被回收,这就意味他能更加快速的响应外界请求

//只有核心线程,没有超时机制,任务队列,没有大小限制    public static ExecutorService newFixedThreadPool(int nThreads) {        return new ThreadPoolExecutor(nThreads, nThreads,                                      0L, TimeUnit.MILLISECONDS,                                      new LinkedBlockingQueue<Runnable>());    }

CachedThreadPool
通过Executors的newCachedThreadPool来创建,他是一种线程数量不定的线程池,他只有非核心线程,其中最大线程数为 Integer.MAX_VALUE,由于这个是一个很大的数字,时间就相当于最大线程数任意大,当线程池中的线程都处于活动中,线程池会创建新的线程来处理任务,否则就用空闲线程处理任务,线程池中的空闲线程都有超时机制,这个超时是60s超过60s限制线程被回收,和FixedThreadPool不同的是,CachedThreadPool的任务队列是个空集合
这将导致任何任务都会立即执行,因为这种状态下无法进行插入任务,这种线程池适合处理大量耗时较少的任务,当整个线程池处于闲置时,线程都会由于超时而终止,这时候几乎不占用任何资源

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

3 ScheduledThreadPool
通过Executors的newScheduledThreadPool来创建,他的核心线程数是固定的,而费和细心线程数是没哟限制的,并且当非核心线程闲置会立刻被回收,这类线程池主要用于执行定时任务和固定周期的重复任务

    public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE,              DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,              new DelayedWorkQueue());    }

4 SingleThreadExecutor

通过Executors的newSingleThreadExecutor来创建
这类线程池只有一个核心线程,他确保所有的任务都在同一个线程中顺序执行,他的意义在于同意外界所有任务到一个线程中,这使得这些任务之间不需要处理线程同步问题

  public static ExecutorService newSingleThreadExecutor() {        return new FinalizableDelegatedExecutorService            (new ThreadPoolExecutor(1, 1,                                    0L, TimeUnit.MILLISECONDS,                                    new LinkedBlockingQueue<Runnable>()));    }

他们的使用一般为

     Runnable runnable = new Runnable() {            @Override            public void run() {                //做一些事情            }        };        ExecutorService executorService = Executors.newFixedThreadPool(4);        executorService.execute(runnable);        ExecutorService executorService1 = Executors.newCachedThreadPool();        executorService1.execute(runnable);        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);        //2s后执行        scheduledExecutorService.schedule(runnable,2000, TimeUnit.MILLISECONDS);        //2s后执行每隔一秒执行一次        scheduledExecutorService.scheduleAtFixedRate(runnable,2000,1000,TimeUnit.MILLISECONDS);        ExecutorService executorService2 = Executors.newSingleThreadExecutor();        executorService2.execute(runnable);