Java并发编程之Executor接口的使用
由类图结构可知:
ThreadPoolExecutor 继承了AbstractExecutorService接口; AbstractExecutorService接口实现了ExecutorService接口; ExecutorService继承了Executor接口; 因此以下部分主要讲解ThreadPoolExecutor类。三、Executor接口中常用的方法void execute(Runnable command) 在将来的某个时间执行给定的命令。 该命令可以在一个新线程,一个合并的线程中或在调用线程中执行,由Executor实现。
四、线程池的创建分为两种方式(主要介绍通过ThreadPoolExecutor方式)注:通过Executors类的方式创建线程池,参考lz此博文链接https://www.jb51.net/article/215163.htm
1.ThreadPoolExecutor类中的构造方法
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue workQueue,defaultHandler)
2、 ThreadPoolExecutor类中构造函数的参数解析
corePoolSize 核心线程最大数量,通俗点来讲就是,线程池中常驻线程的最大数量 maximumPoolSize 线程池中运行最大线程数(包括核心线程和非核心线程) keepAliveTime线程池中空闲线程(仅适用于非核心线程)所能存活的最长时间 unit 存活时间单位,与keepAliveTime搭配使用 workQueue 存放任务的阻塞队列 handler 线程池饱和策略3、ThreadPoolExecutor类创建线程池示例
代码
package com.xz.thread.executor;import java.util.concurrent.*;/** * @description: * @author: xz * @create: 2021-06-16 22:16 */public class Demo { public static void main(String[] args) {ThreadPoolExecutor pool = new ThreadPoolExecutor(3,3,1L, TimeUnit.MINUTES,new LinkedBlockingDeque<>());for(int i=1;i<=5;i++){ pool.execute(new Runnable() {@Overridepublic void run() { System.out.println(Thread.currentThread().getName()); try {Thread.sleep(1000);System.out.println('睡眠一秒钟'); } catch (InterruptedException e) {e.printStackTrace(); }} });} }}
输出结果如下图
结论:无论是创建何种类型线程池(newFixedThreadPool、newSingleThreadExecutor、newCachedThreadPool等等),均会调用ThreadPoolExecutor构造函数。
到此这篇关于Java并发编程之Executor接口的使用的文章就介绍到这了,更多相关Java Executor接口内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章:
