天天看点

线程池—【ThreadPool】—扫盲篇

线程池—【ThreadPool】—扫盲篇

    • 【一】What is the ThreadPool 什么是线程池
    • 【二】How can we use the ThreadPool 我们如何使用它
    • 1.核心数=最大数 线程无缓存时间 使用LinkedBlockingQueue作为阻塞工作队列的单线程执行器的线程池
    • 2.核心数=最大数=n 线程无缓存时间 使用LinkedBlockingQueue作为阻塞工作队列的固定线程执行器的线程池
    • 3.核心数=0,最大数=Interger.MAX_VALUE 线程缓存时间=60S 使用SynchronousQueue作为阻塞工作队列的缓存线程执行器的线程池
    • 4.核心数=n,最大数=Interger.MAX_VALUE 线程无缓存时间 使用DelayedWorkQueue作为阻塞工作队列的定时任务的线程执行器的线程池
    • 【三】Why use the ThreadPool 为什么使用线程池
    • 1.降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
    • 2.提高相应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行。
    • 3.提高线程的可管理性:线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配,调优和监控。

大家好! 写这篇博客的目的是分析一下线程池的使用,做到知其然知其所以然。

The real target is that I was asked the ThreadPool usage in the interview. And I cann’t answer it.

真正目的是因为在面试中被问到线程池的使用,我没有很好的答上来。

【一】What is the ThreadPool 什么是线程池

  1. 池的概念 :用来放一堆相同东西的容器。eg:水池(装的全是水);
    线程池—【ThreadPool】—扫盲篇
  2. 大白话线程池,顾名思义:装的全是线程;
  3. 百度官方说法:
    线程池—【ThreadPool】—扫盲篇
  4. 类比:数据库连接池;
  5. 类图:
    线程池—【ThreadPool】—扫盲篇
  6. 线程池构造方法参数意义:
    线程池—【ThreadPool】—扫盲篇

【二】How can we use the ThreadPool 我们如何使用它

1.核心数=最大数 线程无缓存时间 使用LinkedBlockingQueue作为阻塞工作队列的单线程执行器的线程池

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

2.核心数=最大数=n 线程无缓存时间 使用LinkedBlockingQueue作为阻塞工作队列的固定线程执行器的线程池

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

3.核心数=0,最大数=Interger.MAX_VALUE 线程缓存时间=60S 使用SynchronousQueue作为阻塞工作队列的缓存线程执行器的线程池

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

4.核心数=n,最大数=Interger.MAX_VALUE 线程无缓存时间 使用DelayedWorkQueue作为阻塞工作队列的定时任务的线程执行器的线程池

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

【三】Why use the ThreadPool 为什么使用线程池

1.降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。

2.提高相应速度:当任务到达时,任务可以不需要等到线程创建就能立即执行。

3.提高线程的可管理性:线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配,调优和监控。

参考资料:

《Java并发编程的技术》

JDK8源码:Executor

JDK8源码:ExecutorService

JDK8源码:AbstractExecutorService

JDK8源码:ThreadPoolExecutor

JDK8源码:Executors

JDK8源码:ScheduledThreadPoolExecutor

继续阅读