当前位置:   article > 正文

Java并发编程:ThreadPoolExecutor常用线程池_throw new runtimeerrorexception(null);

throw new runtimeerrorexception(null);

目录

线程池的分类

常用线程池(ThreadPoolExecutor)示例

CachedThreadPool

FixedThreadPool

SingleThreadExecutor

ThreadPoolExecutor类分析

三种线程池(返回ThreadPoolExecutor)构造方法

ThreadPoolExecutor中的成员变量

三种线程池(返回ThreadPoolExecutor类)分析

execute与submit方法


线程池的分类

所有实现了ExecutorService接口(Executor的子接口)的实现类都是线程池,可以分为三大类

  • ForkJoinPool
  • ScheduledThreadPoolExecutor
  • ThreadPoolExecutor

 

具体的线程池,在工具类Executors中预创建了六小类

实现了ThreadPoolExecutor类:

  • ExecutorService newCachedThreadPool():无界线程池
  • ExecutorService newFixedThreadPool():有界线程池
  • ExecutorService newSingleThreadExecutor():单一线程池

实现了ScheduledThreadPoolExecutor类:

  • ScheduledExecutorService newSingleThreadScheduledExecutor() 
  • ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

实现了ForkJoinPool类: 

  • ExecutorService newWorkStealingPool()  

 

当然我们也可以自定义线程池

 

常用线程池(ThreadPoolExecutor)示例

现在有一个任务WorkTask

  1. public class WorkTask implements Runnable{
  2. public void run() {
  3. try {
  4. int r = (int)(Math.random()*10);
  5. Thread.sleep(r*1000);
  6. System.out.println(Thread.currentThread().getId() + " is over");
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. }
  11. }

CachedThreadPool

  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. public class CachedThreadPoolTest {
  4. public static void main(String[] args) {
  5. ExecutorService exec = Executors.newCachedThreadPool();
  6. for(int i=0;i<20;i++){
  7. exec.execute(new WorkTask());
  8. }
  9. exec.shutdown();
  10. }
  11. }

无界线程池,最多可创建Integer.MAX_VALUE个线程,运行结果没有重复的线程号

FixedThreadPool

  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. public class FixedThreadPoolTest {
  4. public static void main(String[] args) {
  5. ExecutorService exe
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/926030
推荐阅读
相关标签
  

闽ICP备14008679号