线程池创建的四种

线程池创建的四种方式都是什么

发布 : Java培训   发布时间:2021-10-12 18:01:48

品牌型号:联想小新Pro13/系统版本:windows10

通过Executors线程池创建的四种方法分别为:

newCachedThreadPool:创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

newFixedThreadPool:创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

newScheduledThreadPool:创建一个定长线程池,支持定时及周期性任务执行。

newSingleThreadExecutor:创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

  1. public class ThreadPoolExecutor extends AbstractExecutorService{//第一个构造方法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. }//第二个构造方法public ThreadPoolExecutor(int corePoolSize,
  9. int maximumPoolSize,
  10. long keepAliveTime,
  11. TimeUnit unit,
  12. BlockingQueue<Runnable> workQueue,
  13. ThreadFactory threadFactory) {
  14. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
  15. threadFactory, defaultHandler);
  16. }//第三个构造方法public ThreadPoolExecutor(int corePoolSize,
  17. int maximumPoolSize,
  18. long keepAliveTime,
  19. TimeUnit unit,
  20. BlockingQueue<Runnable> workQueue,
  21. RejectedExecutionHandler handler) {
  22. this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
  23. Executors.defaultThreadFactory(), handler);
  24. }//第四个也是真正的初始化构造函数public ThreadPoolExecutor(int corePoolSize,
  25. int maximumPoolSize,
  26. long keepAliveTime,
  27. TimeUnit unit,
  28. BlockingQueue<Runnable> workQueue,
  29. ThreadFactory threadFactory,
  30. RejectedExecutionHandler handler) {
  31. if (corePoolSize < 0 ||
  32. maximumPoolSize <= 0 ||
  33. maximumPoolSize < corePoolSize ||
  34. keepAliveTime < 0)
  35. throw new IllegalArgumentException();
  36. if (workQueue == null || threadFactory == null || handler == null)
  37. throw new NullPointerException();
  38. this.corePoolSize = corePoolSize;
  39. this.maximumPoolSize = maximumPoolSize;
  40. this.workQueue = workQueue;
  41. this.keepAliveTime = unit.toNanos(keepAliveTime);
  42. this.threadFactory = threadFactory;
  43. this.handler = handler;
  44. }}

其它答案
牛仔很忙2020-06-22 18:56:36

newCachedThreadPool创建可缓存线程池、newFixedThreadPool创建定长线程池、newScheduledThreadPool创建定长线程池、newSingleThreadExecutor创建单线程化线程池


 相关推荐