线程池:一种线程使用模式。线程过多会带来调度开销。

  • 一池N线程

    1. Executors.newFixedThreadPool(int)
  • 一个任务一个任务执行,一池一线程

    1. Executors.newSingleThreadExecutor()
  • 线程池根据需求创建线程,可扩容,遇强则强

    1. Executors.newCachedThreadPool()

    实际开发中不会使用上面三种方式创建

    image.png

    线程池7个参数

    线程池的创建底层都是调用了如下方法

    1. public ThreadPoolExecutor(int corePoolSize,
    2. int maximumPoolSize,
    3. long keepAliveTime,
    4. TimeUnit unit,
    5. BlockingQueue<Runnable> workQueue) {
    6. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
    7. Executors.defaultThreadFactory(), defaultHandler);
    8. }

    各个参数的意思
    image.png
    image.pngimage.png
    JDK内置的拒绝策略

自定义线程池

  1. package com.daijunyi.pool;
  2. import java.util.Random;
  3. import java.util.concurrent.*;
  4. public class PoolTest {
  5. public static void main(String[] args) {
  6. ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
  7. 5,
  8. 2L,
  9. TimeUnit.SECONDS,
  10. new ArrayBlockingQueue<>(3),
  11. Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
  12. try {
  13. for (int i=0;i<20;i++){
  14. threadPoolExecutor.execute(()->{
  15. System.out.println(Thread.currentThread().getName()+"执行");
  16. try {
  17. TimeUnit.SECONDS.sleep(new Random().nextInt(2));
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. System.out.println(Thread.currentThread().getName()+"完成----");
  22. });
  23. }
  24. }finally {
  25. //执行完毕关闭线程池
  26. threadPoolExecutor.shutdown();
  27. }
  28. }
  29. }