Android - 线程池

老婆保佑,代码无BUG

前言

2018 准备换工作,也得好好准备面试,PS,小伙伴需要招人不,求推荐

面试题: 说说你对JAVA 线程池的理解


目录

  • 一:线程池的优点
  • 二:线程种类
  • 三:使用介绍
      1. FixedThreadPool (定长线程池)
      1. CacheThreadPool (可缓存线程池)
      1. SingleThreadExecutor (单线程化线程池)
      1. ScheduledThreadPool (定时线程池)
  • 四:源码分析
  • 五:ThreadPoolExecutor参数
  • 参考

一:线程池的优点

  • 减少在创建和销毁线程上所花的时间以及系统资源的开销。
  • 有效控制线程并发,避免大量线程之间因抢占资源导致阻塞现象

二:线程种类

  • FixedThreadPool (定长线程池)
  • SingleThreadExecutor (单线程化线程池)
  • CachedThreadPool (可缓存线程池)
  • ScheduledThreadPool (定时线程池)

三:使用介绍

1. FixedThreadPool

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  

特点:

  • 这是一种数量固定的线程池,当线程处于空闲的时候,并不会被回收,除非线程池被关闭.
  • 当所有的线程都处于活动状态时,新任务都会处于等待状态,直到有线程空闲出来.
  • 由于FixedThreadPool中只有核心线程并且这些核心线程不会被回收,这意味着它能够更加快速地响应外界的请求.

eg:

    private void init_TestThread() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(3000);
                    Log.d("TAG", "run: " + finalI + "  thread: "+Thread.currentThread().getName());
                }
            };
            fixedThreadPool.execute(runnable);
        }
    }

log:

02-11 02:52:42.609 4305-4464/com.cpsc.rxjavademo D/TAG: run: 1  thread: pool-3-thread-2
02-11 02:52:42.622 4305-4463/com.cpsc.rxjavademo D/TAG: run: 0  thread: pool-3-thread-1
02-11 02:52:42.631 4305-4465/com.cpsc.rxjavademo D/TAG: run: 2  thread: pool-3-thread-3
02-11 02:52:45.612 4305-4464/com.cpsc.rxjavademo D/TAG: run: 3  thread: pool-3-thread-2
02-11 02:52:45.625 4305-4463/com.cpsc.rxjavademo D/TAG: run: 4  thread: pool-3-thread-1
02-11 02:52:45.634 4305-4465/com.cpsc.rxjavademo D/TAG: run: 5  thread: pool-3-thread-3
02-11 02:52:48.614 4305-4464/com.cpsc.rxjavademo D/TAG: run: 6  thread: pool-3-thread-2
02-11 02:52:48.628 4305-4463/com.cpsc.rxjavademo D/TAG: run: 7  thread: pool-3-thread-1
02-11 02:52:48.636 4305-4465/com.cpsc.rxjavademo D/TAG: run: 8  thread: pool-3-thread-3
02-11 02:52:51.617 4305-4464/com.cpsc.rxjavademo D/TAG: run: 9  thread: pool-3-thread-2

2. CacheThreadPool

 ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

特点:

  • 它是一种线程数量不定的线程池,它只有非核心线程,并且其最大线程数为Integer.MAX_VALUE(也就相当于线程池的线程数量可以无限大).

  • 当线程池中所有线程都处于活动的状态时,线程池会创建新的线程来处理新任务,否则就会复用空闲线程来处理.

eg:

 private void init_TestThread() {
        ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(3000);
                    Log.d("TAG", "run: " + finalI + "  thread: "+Thread.currentThread().getName());
                }
            };
            fixedThreadPool.execute(runnable);
        }
    }

log:

02-11 02:54:16.162 4305-4510/com.cpsc.rxjavademo D/TAG: run: 0  thread: pool-4-thread-1
02-11 02:54:16.164 4305-4511/com.cpsc.rxjavademo D/TAG: run: 1  thread: pool-4-thread-2
02-11 02:54:16.169 4305-4512/com.cpsc.rxjavademo D/TAG: run: 2  thread: pool-4-thread-3
02-11 02:54:16.170 4305-4513/com.cpsc.rxjavademo D/TAG: run: 3  thread: pool-4-thread-4
02-11 02:54:16.172 4305-4514/com.cpsc.rxjavademo D/TAG: run: 4  thread: pool-4-thread-5
02-11 02:54:16.173 4305-4515/com.cpsc.rxjavademo D/TAG: run: 5  thread: pool-4-thread-6
02-11 02:54:16.176 4305-4516/com.cpsc.rxjavademo D/TAG: run: 6  thread: pool-4-thread-7
02-11 02:54:16.180 4305-4517/com.cpsc.rxjavademo D/TAG: run: 7  thread: pool-4-thread-8
02-11 02:54:16.182 4305-4518/com.cpsc.rxjavademo D/TAG: run: 8  thread: pool-4-thread-9
02-11 02:54:16.184 4305-4520/com.cpsc.rxjavademo D/TAG: run: 9  thread: pool-4-thread-10

3. SingleThreadExecutor

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); 

特点

  • 这类线程池内部只有一个核心线程,它确保所有的任务都在同一个线程中按顺序执行.

eg:


    private void init_TestThread() {
        ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(3000);
                    Log.d("TAG", "run: " + finalI + "  thread: "+Thread.currentThread().getName());
                }
            };
            fixedThreadPool.execute(runnable);
        }
    }

log:

02-11 02:55:26.466 4305-4557/com.cpsc.rxjavademo D/TAG: run: 0  thread: pool-5-thread-1
02-11 02:55:29.466 4305-4557/com.cpsc.rxjavademo D/TAG: run: 1  thread: pool-5-thread-1
02-11 02:55:32.472 4305-4557/com.cpsc.rxjavademo D/TAG: run: 2  thread: pool-5-thread-1
02-11 02:55:35.473 4305-4557/com.cpsc.rxjavademo D/TAG: run: 3  thread: pool-5-thread-1
02-11 02:55:38.475 4305-4557/com.cpsc.rxjavademo D/TAG: run: 4  thread: pool-5-thread-1
02-11 02:55:41.476 4305-4557/com.cpsc.rxjavademo D/TAG: run: 5  thread: pool-5-thread-1
02-11 02:55:44.478 4305-4557/com.cpsc.rxjavademo D/TAG: run: 6  thread: pool-5-thread-1
02-11 02:55:47.479 4305-4557/com.cpsc.rxjavademo D/TAG: run: 7  thread: pool-5-thread-1
02-11 02:55:50.480 4305-4557/com.cpsc.rxjavademo D/TAG: run: 8  thread: pool-5-thread-1
02-11 02:55:53.481 4305-4557/com.cpsc.rxjavademo D/TAG: run: 9  thread: pool-5-thread-1

4. ScheduledThreadPool

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);  

特点

  • 它的核心线程数量是固定的,而非核心线程数是没有限制的,并且当非核心线程闲置时会被立即回收.

eg:

 private void init_TestThread() {
        ExecutorService fixedThreadPool = Executors.newScheduledThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(3000);
                    Log.d("TAG", "run: " + finalI + "  thread: "+Thread.currentThread().getName());
                }
            };
            fixedThreadPool.execute(runnable);
        }
    }

log:


02-11 03:41:32.230 6981-7045/com.cpsc.rxjavademo D/TAG: run: 0  thread: pool-1-thread-1
02-11 03:41:32.236 6981-7046/com.cpsc.rxjavademo D/TAG: run: 1  thread: pool-1-thread-2
02-11 03:41:32.239 6981-7047/com.cpsc.rxjavademo D/TAG: run: 2  thread: pool-1-thread-3
02-11 03:41:35.233 6981-7045/com.cpsc.rxjavademo D/TAG: run: 3  thread: pool-1-thread-1
02-11 03:41:35.238 6981-7046/com.cpsc.rxjavademo D/TAG: run: 4  thread: pool-1-thread-2
02-11 03:41:35.240 6981-7047/com.cpsc.rxjavademo D/TAG: run: 5  thread: pool-1-thread-3
02-11 03:41:38.234 6981-7045/com.cpsc.rxjavademo D/TAG: run: 6  thread: pool-1-thread-1
02-11 03:41:38.240 6981-7046/com.cpsc.rxjavademo D/TAG: run: 7  thread: pool-1-thread-2
02-11 03:41:38.242 6981-7047/com.cpsc.rxjavademo D/TAG: run: 8  thread: pool-1-thread-3
02-11 03:41:41.237 6981-7045/com.cpsc.rxjavademo D/TAG: run: 9  thread: pool-1-thread-1

四:源码分析

  • FixedThreadPool
 public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue());
    }
  • CacheThreadPool
  public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue());
    }
  • SingleThreadExecutor
 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue()));
    }
  • ScheduledThreadPool

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


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

五:ThreadPoolExecutor参数

 public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue workQueue) {}

参数说明

参数 说明
corePoolSize 线程池中核心线程的数量
maximumPoolSize 线程池中最大线程数量
keepAliveTime 非核心线程的超时时长,当系统中非核心线程闲置时间超过keepAliveTime之后,则会被回收。如果ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,则该参数也表示核心线程的超时时长
unit 用于指定keepAliveTime参数单位,有纳秒、微秒、毫秒、秒、分、时、天等
workQueue 线程池中的任务队列,该队列主要用来存储已经被提交但是尚未执行的任务。存储在这里的任务是由ThreadPoolExecutor的execute方法提交来的。

参考

深入理解java线程池—ThreadPoolExecutor

Android多线程:线程池ThreadPool 全面解析

你可能感兴趣的:(Android - 线程池)