租凭境外服务器做违规网站,医院风格 wordpress,微信公众平台运营中心电话,顺徳网站建设公司有哪些线程池
什么是线程池#xff1f; 线程池#xff1a;一种基于池化思想管理和使用线程的机制
线程池常用类和接口
ExecutorService接口#xff1a;进行线程池的操作访问Executors类#xff1a;创建线程池的工具类ThreadPoolExecutor及其子类#xff1a;封装线程池的核心参…线程池
什么是线程池 线程池一种基于池化思想管理和使用线程的机制
线程池常用类和接口
ExecutorService接口进行线程池的操作访问Executors类创建线程池的工具类ThreadPoolExecutor及其子类封装线程池的核心参数和运行机制
线程池常见的方法
执行无参返回值的线程任务void execute(Runnable command);提交有返回值的线程任务FutureT submit(CallableT task);关闭线程池void shutdown();或shutdownNow();等待线程池关闭boolean awaitTermination(long timeout,TimeUnit unit);
线程池执行流程 提交一个新的线程任务线程池判断池中是否存在空闲线程如果存在分配空闲线程执行线程任务如果线程池中没有空闲的线程则判断核心线程数是否超出设定未超出则创建核心线程用于执行新提交的线程任务如果已超出核心线程数则往工作队列中存放工作队列先进先出当出现空闲线程时从工作队列中依次取出线程任务如果工作队列已经存满则判断最大线程数是否超出未超出最大线程数则创建非核心线程执行线程任务如果已达到了最大线程数则启动拒绝策略
线程数的配置参数
corePoolSize线程池核心线程数可以理解为线程池维护的最小线程数核心线程创建后不会被回收。大于核心线程数的吸纳成在空闲时间超过keepAliveTime后会被回收
maximumPoolSize线程池最大线程数线程池允许创建的最大线程数量包含核心线程池数量
keepAliveTime非核心线程存活时间当一个可被回收的线程的空闲时间大于keepAliveTime就会被回收
TimeUnit时间单位参数keepAliveTime的时间单位
BlockingQueue阻塞工作队列用于存储等待执行的任务
ThreadFactory线程工厂用于创建线程以及自定义线程名称需要实现ThreadFactory接口
RejectedExecutionHandler拒绝策略当线程池中的线程耗尽并且工作队列已满时新提交的任务将会启动拒绝策略处理
线程池的分类 FixedThreadPool线程数固定的线程池 通过Executors.newFixedThreadPool(n);方法创建 // 创建有十个线程的线程池
Executors.newFixedThreadPool(10);// Executors.newFixedThreadPool(n)方法源码
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueueRunnable());
}通过源码FixedThreadPool线程池的核心线程数和最大线程数都是传入的参数所以是固定线程数的线程池
CacheThreadPool线程数根据任务动态调整的线程池 通过Executors.newCachedThreadPool();方法创建 // 创建一个CacheThreadPool线程池
Executors.newCachedThreadPool();// 源码
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueueRunnable());
}通过源码CacheThreadPool线程池的核心线程数为0最大线程数为Integer的最大值非核心线程的存活时间为60s SingleThreadPool仅提供一个单线程的线程池 通过Executors.*newSingleThreadExecutor*();方法创建 // 创建一个SingleThreadPool线程池
Executors.newSingleThreadExecutor();// 源码
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueueRunnable()));
}通过源码SingleThreadPool线程池的核心线程数和最大线程数都为1其他线程的存储时间为0 ScheduledThreadPool能实现定时、周期性任务的线程池 通过Executors.newScheduledThreadPool(n);方法创建 // 创建一个ScheduledThreadPool线程池
Executors.newScheduledThreadPool(10);// 源码
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);
}⬇⬇⬇⬇⬇⬇// new ScheduledThreadPoolExecutor(corePoolSize);方法源码
public ScheduledThreadPoolExecutor(int corePoolSize) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue());
}通过源码ScheduledThreadPool线程池的核心线程数为传入的参数最大线程数为Integer类型的最大值非核心线程的存活时间为0空闲立马被回收