2020最新Java线程池入门(超详细)

转 https://blog.csdn.net/weixin_43893397/article/details/104361154

【1】代码示例 

/*** 线程池测试-自定义线程池创建方式* @since 2021/03/23 */
public class ThreadPoolMain2 {public static void main(String[] args) throws Exception {newMethod();}public static void newMethod() throws InterruptedException {/*** 开启一个线程池  默认线程是10个* 使用默认线程工厂* 拒绝策略为CallerRunsPolicy策略,让后面的线程先等待 */ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());//书写一个循环  模拟100个用户同时访问for (int request = 0; request< 100;request ++){final int temp = request; //开启一个线程threadPoolExecutor.execute(() ->{System.out.println("任务" + temp +"开始执行...");/*** 睡10秒 */try {Thread.sleep(1000L * 3);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("任务" + temp +"执行结束...");});}}
}

【2】 ThreadPoolExecutor 构造器解析

/*** Creates a new {@code ThreadPoolExecutor} with the given initial* parameters.** @param corePoolSize the number of threads to keep in the pool, even*        if they are idle, unless {@code allowCoreThreadTimeOut} is set* @param maximumPoolSize the maximum number of threads to allow in the*        pool* @param keepAliveTime when the number of threads is greater than*        the core, this is the maximum time that excess idle threads*        will wait for new tasks before terminating.* @param unit the time unit for the {@code keepAliveTime} argument* @param workQueue the queue to use for holding tasks before they are*        executed.  This queue will hold only the {@code Runnable}*        tasks submitted by the {@code execute} method.* @param threadFactory the factory to use when the executor*        creates a new thread* @param handler the handler to use when execution is blocked*        because the thread bounds and queue capacities are reached* @throws IllegalArgumentException if one of the following holds:<br>*         {@code corePoolSize < 0}<br>*         {@code keepAliveTime < 0}<br>*         {@code maximumPoolSize <= 0}<br>*         {@code maximumPoolSize < corePoolSize}* @throws NullPointerException if {@code workQueue}*         or {@code threadFactory} or {@code handler} is null*/public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {

【3】参数解析

序号参数名描述中文
1corePoolSizethe number of threads to keep in the pool, even if they are idle, unless {@code allowCoreThreadTimeOut} is set.除非设置了{@code allowCoreThreadTimeOut},否则即使它们处于空闲状态也要保留在池中的线程数。
2maximumPoolSize the maximum number of threads to allow in the pool池中允许的最大线程数
3keepAliveTimewhen the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.当线程数大于内核数时,这是多余的空闲线程将在终止之前等待新任务的最长时间。
4unitthe time unit for the {@code keepAliveTime} argument{@code keepAliveTime}参数的时间单位
5workQueue

 the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.

在执行任务之前用于保留任务的队列。 此队列将仅保存execute方法提交的Runnable任务。
6threadFactorythe factory to use when the executorcreates a new thread.执行程序创建新线程时要使用的工厂。
7handler

 the handler to use when execution is blockedbecause the thread bounds and queue capacities are reached.

当执行被阻塞时使用的处理程序,因为达到了线程界限和队列容量。

【4】抛弃策略

// 当任务无法添加到阻塞队列时的处理策略-直接抛出异常RejectedExecutionHandler rejectHandler1 = new ThreadPoolExecutor.AbortPolicy(); // -会调用当前线程池的所在的线程去执行被拒绝的任务。RejectedExecutionHandler rejectHandler2 = new ThreadPoolExecutor.CallerRunsPolicy(); // 会抛弃任务队列中最旧的任务也就是最先加入队列的,再把这个新任务添加进去。RejectedExecutionHandler rejectHandler3 = new ThreadPoolExecutor.DiscardOldestPolicy();// 会让被线程池拒绝的任务直接抛弃,不会抛异常也不会执行。RejectedExecutionHandler rejectHandler4 = new ThreadPoolExecutor.DiscardPolicy(); RejectedExecutionHandler rejectHandler = rejectHandler4; ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),Executors.defaultThreadFactory(), rejectHandler);

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/330113.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HDFS的诞生

转载自 HDFS的诞生 1牛刀小试 张大胖找了个实习的工作&#xff0c; 第一天上班Bill师傅给他分了个活儿&#xff1a;日志分析。张大胖拿到了师傅给的日志文件&#xff0c;大概有几十兆&#xff0c;打开一看&#xff0c; 每一行都长得差不多&#xff0c;类似这样&#xff1a;212.…

项目背景怎么描述_产品经理写简历,如何让「项目经验」更出众?

项目经验怎么写更出众&#xff1f;时间长但效果一般的项目经验要不要写&#xff1f;没有项目经验怎么办&#xff1f;本文凭借作者自己长期招聘产品、阅读大量简历所积累的经验解答了这三个问题&#xff0c;希望对你有所帮助。产品经理写简历时&#xff0c;都会通过项目案例来证…

一致性Hash算法原理

前言 当在需要将数据分发到多个数据库/缓存&#xff0c;或将请求分发给多个服务节点时&#xff0c;不可避免的会遇到以下问题&#xff1a; 如何将数据均匀的分散到各个节点中&#xff0c;并且尽量的在加减节点时能使受影响的数据最少。 选择节点的方法 随机放置 从多个节点…

转: java多线程-ThreadPoolExecutor的拒绝策略RejectedExecutionHandler

转自&#xff1a; https://blog.csdn.net/qq_25806863/article/details/71172823 概述 原文地址 http://blog.csdn.net/qq_25806863/article/details/71172823 在分析ThreadPoolExecutor的构造参数时&#xff0c;有一个RejectedExecutionHandler参数。 RejectedExecutionH…

已知两点坐标如何快速增加其他坐标_「测绘精选」坐标转换概述

引言&#xff1a;这篇“坐标转换概述”献给各位&#xff0c;可以对坐标转换有一个大致地、整体地了解。文中有些名词是为了便于表达而自创的&#xff0c;大家不用考据、较真。一、静态坐标和动态坐标(1)静态坐标传统大地测量没有考虑板块运动对坐标的影响。虽然板块运动客观存在…

什么是G1垃圾回收算法

转载自 什么是G1垃圾回收算法为解决CMS算法产生空间碎片和其它一系列的问题缺陷&#xff0c;HotSpot提供了另外一种垃圾回收策略&#xff0c;G1&#xff08;Garbage First&#xff09;算法&#xff0c;通过参数 -XX:UseG1GC来启用&#xff0c;该算法在JDK 7u4版本被正式推出&am…

一文理清RocketMQ顺序消费、重复消费、消息丢失问题

前言 在使用消息队列时不可避免的会遇到顺序消费、重复消费、消息丢失三个问题。在一次面试字节的时候&#xff0c;面试官问到如何保证顺序消费&#xff0c;当时回答不太准确&#xff0c;特意此文回顾如何解决顺序消费、重复消费、消息丢失三个问题。 重复消费 解决重复消费…

一道丧心病狂的java面试题

转载自 一道丧心病狂的java面试题无意中了解到如下题目&#xff0c;觉得蛮好。 题目如下&#xff1a; public class TestSync2 implements Runnable {int b 100; synchronized void m1() throws InterruptedException {b 1000;Thread.sleep(500); //6System.out.pri…

水晶报表图形位置_看了我用Excel做的年度报表,老板直夸好

2020年前5个月&#xff0c;最火爆的莫过于口罩。口罩的整条产业链都变得炙手可热&#xff0c;口罩、口罩机、炒熔喷布、聚丙烯等等相关企业的业务数据往往都是去年的几倍。那我们现在作为一家“表姐牌”的口罩厂的员工&#xff0c;老板叫我用Excel做一个既酷炫又简洁的年度报表…

Mysql优化(三):优化order by

MySQL中的两种排序方式 .通过有序索引顺序扫描直接返回有序数据 因为索引的结构是B树&#xff0c;索引中的数据是按照一定顺序进行排列的&#xff0c;所以在排序查询中如果能利用索引&#xff0c;就能避免额外的排序操作。EXPLAIN分析查询时&#xff0c;Extra显示为Using inde…

漫画:什么是服务熔断

转载自 漫画&#xff1a;什么是服务熔断什么是服务熔断&#xff1f;熔断这一概念来源于电子工程中的断路器&#xff08;Circuit Breaker&#xff09;。在互联网系统中&#xff0c;当下游服务因访问压力过大而响应变慢或失败&#xff0c;上游服务为了保护系统整体的可用性&#…

rabbitmq手动确认ack

【README】 参考 https://blog.csdn.net/u012943767/article/details/79300673 &#xff1b; 【0】声明交换机&#xff0c;队列 与绑定 /*** 交换机&#xff0c;队列声明与绑定 */ public class AckDeclarer {/** 确认交换机 */public static final String ACK_EXCHANGE2 &q…

python图片保存_python读取和保存图片5种方法对比

python读取和保存图片5种方法对比 python中对象之间的赋值是按引用传递的&#xff0c;如果需要拷贝对象&#xff0c;需要用到标准库中的copy模块 方法一&#xff1a;利用 PIL 中的 Image 函数 这个函数读取出来不是 array 格式&#xff0c;这时候需要用 np.asarray(im) 或者 np…

finally块不被执行的情况总结

finally块的作用 通常用于处理善后工作。当try块里出现异常时&#xff0c;会立即跳出try块&#xff0c;到catch块匹配对应的异常&#xff0c;执行catch块里的语句。此时&#xff0c;可能在try块里存在打开的文件没关闭&#xff0c;连接的网络没断开&#xff0c;这部分资源是GC…

rabbitmq生产者基于事务实现发送确认

【README】 业务场景&#xff1a; 业务处理伴随消息的发送&#xff0c;业务处理失败&#xff08;事务回滚&#xff09;后要求消息不发送。 补充1&#xff1a;ACK与CONFIRM的区别 ACK-消费者消费成功后确认&#xff1b;&#xff08;消费者确认已收到&#xff09; CONFIRM-事…

什么是CAP定理

转载自 什么是CAP定理计算机界有很多高大上又难于理解的术语&#xff0c;CAP就是其中之一&#xff0c; 什么一致性&#xff08;Consistency&#xff09;&#xff0c; 可用性&#xff08;Availability&#xff09;&#xff0c; 分区容错性&#xff08;Partition tolerance&#…

python找不到指定的文件夹里_Python环球网在Unix中的指定文件路径中找不到*.txt

我在Windows环境中写了一些文件&#xff0c;我在转换文件时遇到了麻烦。在Windows中&#xff0c;我通常使用类似以下内容读取目录中的所有.txt文件&#xff1a;pathtotxt "C:\\Text Data\\EJC\\Philosophical Transactions 1665-1678\\*\\*.txt" for file in glob.g…

从开发者角度谈Mysql主键

转载自 从开发者角度谈Mysql主键说在前面零度mysql一直比较薄弱&#xff0c;俗话说的好&#xff0c;不会mysql的程序员不是好程序员&#xff0c;刚刚好认识mysql大牛刘龘刘&#xff0c;刚刚好就有了这些文章&#xff0c;主要是刘龘刘大牛写的&#xff0c;零度稍微修改成文&…

JVM内存结构分析:为什么需要S0和S1?

一、为什么会有年轻代 我们先来屡屡&#xff0c;为什么需要把堆分代&#xff1f;不分代不能完成他所做的事情么&#xff1f;其实不分代完全可以&#xff0c;分代的唯一理由就是优化GC性能。你先想想&#xff0c;如果没有分代&#xff0c;那我们所有的对象都在一块&#xff0c;…

rabbitmq-消息追踪rabbitmq_tracing

【README】 消息中心的消息追踪需要使用 Trace 实现&#xff0c;Trace是 rabbitmq用于记录每一次发送的消息&#xff1b;方便开发者调试&#xff0c;排错。可通过插件形式提供可视化界面。 【1】 开启消息追踪 1&#xff09;消息追踪通过 rabbitmq的插件 trace 来实现&#x…