线程池的创建

1.常见的线程启动方式
方式1

 Thread(){
          run {
         Log.e("ThreadPoolActivity","current thread name is ...  "+Thread.currentThread().name)
           }
        }.start()

方式2

Thread(MyThread()).start()
private class MyThread:Runnable{
       override fun run() {
           Log.e("ThreadPoolActivity","MyThread current thread name is ...  "+Thread.currentThread().name)
       }
    }

2.线程池常用方法
我们先来看第一个。可缓存的线程池。

val threadPoolCached=Executors.newCacheThreadPool()    //

点击查看源码如下

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

第二个,固定长度的线程池
val threadPoolFixed=Executors.newFixedThreadPool(1) //
点击查看源码如下

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

第三个,单一长度线程池
val threadPoolSingle=Executors.newSingleThreadExecutor() //

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

从上面常见的三种线程池源码我们很容易看出,他们都用的是ThreadPoolExecutor的构造函数来创建的。我们继续看下ThreadPoolExecutor的源码

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

分析:corePoolSize指的是核心线程数,maximumPoolSize是指最大线程池中线程数,
keepAliveTime是指当前存在的线程数大于核心线程数的时候,这些多余的线程所允许的线程等待时长。unit是指上面等待时长的单位。workQueue是一个阻塞队列。
keepAliveTime源码中描述如下:

@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.

Executors.defaultThreadFactory()使用的是工厂模式,它创建了一个默认的线程工厂DefaultThreadFactory,实现(implements)了ThreadFactory,重写了newThread方法。

 public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }

defaultHandler实际是AbortPolicy,它实现了接口RejectedExecutionHandler,重写了rejectedExecution(翻译:拒绝执行)方法。
defaultHandler指的是什么呢,官方标注如下:

the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached

翻译过来就是:执行被阻止时要使用的处理程序,因为已达到线程边界和队列容量

private static final RejectedExecutionHandler defaultHandler =
        new AbortPolicy();

AbortPolicy源码

 public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
  1. 引入
    ReentrantLock重入锁
    跟sychronize比较像,用法也基本一样。
    .ReentrantLock和synchronized都是独占锁,只允许线程互斥的访问临界区。但是实现上两者不同:synchronized加锁解锁的过程是隐式的,用户不用手动操作,优点是操作简单,但显得不够灵活。一般并发场景使用synchronized的就够了;ReentrantLock需要手动加锁和解锁,且解锁的操作尽量要放在finally代码块中,保证线程正确释放锁。ReentrantLock操作较为复杂,但是因为可以手动控制加锁和解锁过程,在复杂的并发场景中能派上用场。
    ReentrantLock相比sychronize来说还有些优点,比如可以获取公平锁,可以避免死锁等。具体有兴趣的小伙伴可以自己研究哈,我们这里不做过多描述。

4.BlockingQueue阻塞队列
从上面三种线程池的创建,我们很容易发现除了数量上的差异,还有BlokingQueue类型上的差异。查看LinkedBlockingQueue和SynchronousQueue源码,我们也很容易得出他们都实现了BlockingQueue,BlockingQueue实际上是一个接口。

我们先来看下一张关系表,我们这里主要介绍的是BlockingQueue直接实现类。


image.png

先看下ArrayBlockingQueue,顾名思义,内部使用的是数组的形式来实现的。

ArrayBlockingQueue有三个构造函数
1、ArrayBlockingQueue(int)

接收一个整型的参数,这个整型参数指的是队列的长度,其定义如下,

public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
}

可以看到这个方法调用的是ArrayBlockingQueue(int,boolean)方法,那么看下这个方法,

2、ArrayBlockingQueue(int,boolean)

接收两个参数,一个整型,一个boolean类型,前边已经知道整型参数是队列的长度,那么boolean类型参数代表什么意思那,其定义如下,

public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

可以看到在这个构造方法,对items进行了数组初始化,boolean类型的参数是作为可重入锁的参数进行初始化,规定可重入锁是公平还是不公平,默认为false,另外初始化了notEmpty、notFull两个信号量。

3、ArrayBlockingQueue(int,boolean,Collection<? extends E>)

接收三个参数,前两个跟上面的一样,第三个集合类型,此构造方法不常用,其定义如下,

public ArrayBlockingQueue(int capacity, boolean fair,
                              Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // 获取锁
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock(); 、、释放锁
        }
    }
4. offer方法,向队列中放入一个元素.

如果队列中的元素数量和队列长度相等,则直接返回false,否则执行enqueue方法

public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

   private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length) putIndex = 0;
        count++;
        notEmpty.signal();
    }

5. offer方法,向队列中放入一个元素.

如果队列中的元素数量和队列长度相等,则直接返回false,否则执行enqueue方法

public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length) takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

其他的像add/peek,put/take方法,内部都使用的是equeue和dequeue方法。

4。其他的像LinkedBlockingQueue(跟ArrayBlockingQueue比较像,但他使用的是Node节点,内部使用了两个重入锁,一个控制put,一个控制take,这样我们就可以同时进行放入和取出操作了,但有一定风险。)
再比如PriorityBlockingQueue,Priority是优先的意思,就是我们可以根据线程任务权重对他进行优先级排列,内部是使用二叉树的排序规则。我们可以自定义一个Comparator比较器,自定义这个排序规则等等。
SychronousQueue是无界的,是一种无缓冲的等待队列,但是由于该Queue本身的特性,在某次添加元素后必须等待其他线程取走后才能继续添加;可以认为SynchronousQueue是一个缓存值为1的阻塞队列,但是 isEmpty()方法永远返回是true,remainingCapacity() 方法永远返回是0,remove()和removeAll() 方法永远返回是false,iterator()方法永远返回空,peek()方法永远返回null。
DelayQueue显而易见,他是一个跟延时有关的阻塞队列,队列的执行顺序并不是FIFO(先进先出),而是每个任务都有一个延时时长,谁先倒计时结束,谁先执行。比如淘宝下单后如果三十分钟之内没有付款就会自动取消订单。

具体的源码有兴趣的小伙伴自己去看源码,这里我就不多讲了,网上针对这几种阻塞队列的源码都有很详细的解析。我这里也主要是为了给大家引入一下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ThreadPoolExecutor代码中的注释 ExcutorService 尽可能使用线程池里的Thread来...
    李太太的碎碎念阅读 409评论 0 0
  • BlockingQueue ThreadPoolExecutor corePoolSize:核心池的大小,这个参数...
    iHelin阅读 187评论 0 0
  • 线程创建和销毁过程花销是比较大的,而频繁创建和销毁,会消耗较大的系统资源时间也有可能导致系统资源不足(线程池可以统...
    小码毅阅读 173评论 0 0
  • 如果你要开启线程执行任务,你会怎么做? 开启一个线程,然后串行执行所有任务 一个任务开启一个线程,任务不会再等待,...
    囧囧有神2号阅读 327评论 0 0
  • 线程池的作用:降低资源消耗,提高响应速度,提高线程的可管理性ThreadPoolExecutor是java.uti...
    发量惊人媛阅读 77评论 0 0