java excutorthread_Java中ThreadPoolExecutor的参数理解

一、使用Executors创建线程池

之前创建线程的时候都是用的Executors的newFixedThreadPool(),newSingleThreadExecutor(),newCachedThreadPool()这三个方法。当然Executors也是用不同的参数去new ThreadPoolExecutor

1. newFixedThreadPool()

创建线程数固定大小的线程池。 由于使用了LinkedBlockingQueue所以maximumPoolSize 没用,当corePoolSize满了之后就加入到LinkedBlockingQueue队列中。每当某个线程执行完成之后就从LinkedBlockingQueue队列中取一个。所以这个是创建固定大小的线程池。

public static ExecutorService newFixedThreadPool(int nThreads) {

return new ThreadPoolExecutor(nThreads, nThreads,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue());

}

public ThreadPoolExecutor(int corePoolSize,

int maximumPoolSize,

long keepAliveTime,

TimeUnit unit,

BlockingQueue workQueue) {

this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,

Executors.defaultThreadFactory(), defaultHandler);

}

2.newSingleThreadPool()

创建线程数为1的线程池,由于使用了LinkedBlockingQueue所以maximumPoolSize 没用,corePoolSize为1表示线程数大小为1,满了就放入队列中,执行完了就从队列取一个。

public static ExecutorService newSingleThreadExecutor() {

return new FinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue()));

}

3.newCachedThreadPool()

创建可缓冲的线程池。没有大小限制。由于corePoolSize为0所以任务会放入SynchronousQueue队列中,SynchronousQueue只能存放大小为1,所以会立刻新起线程,由于maxumumPoolSize为Integer.MAX_VALUE所以可以认为大小为2147483647。受内存大小限制。

public static ExecutorService newCachedThreadPool() {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue());

}

public ThreadPoolExecutor(int corePoolSize,

int maximumPoolSize,

long keepAliveTime,

TimeUnit unit,

BlockingQueue workQueue) {

this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,

Executors.defaultThreadFactory(), defaultHandler);

}

二、使用ThreadPoolExecutor创建线程池

ThreadPoolExecutor的构造函数

public ThreadPoolExecutor(int corePoolSize,

int maximumPoolSize,

long keepAliveTime,

TimeUnit unit,

BlockingQueue workQueue,

ThreadFactory threadFactory,

RejectedExecutionHandler handler) {

if (corePoolSize 

maximumPoolSize <= 0 ||

maximumPoolSize 

keepAliveTime 

throw new IllegalArgumentException();

if (workQueue == null || threadFactory == null || handler == null)

throw new NullPointerException();

this.corePoolSize = corePoolSize;

this.maximumPoolSize = maximumPoolSize;

this.workQueue = workQueue;

this.keepAliveTime = unit.toNanos(keepAliveTime);

this.threadFactory = threadFactory;

this.handler = handler;

}

参数:

1、corePoolSize核心线程数大小,当线程数

2、maximumPoolSize 最大线程数, 当线程数 >= corePoolSize的时候,会把runnable放入workQueue中

3、keepAliveTime  保持存活时间,当线程数大于corePoolSize的空闲线程能保持的最大时间。

4、unit 时间单位

5、workQueue 保存任务的阻塞队列

6、threadFactory 创建线程的工厂

7、handler 拒绝策略

任务执行顺序:

1、当线程数小于corePoolSize时,创建线程执行任务。

2、当线程数大于等于corePoolSize并且workQueue没有满时,放入workQueue中

3、线程数大于等于corePoolSize并且当workQueue满时,新任务新建线程运行,线程总数要小于maximumPoolSize

4、当线程总数等于maximumPoolSize并且workQueue满了的时候执行handler的rejectedExecution。也就是拒绝策略。

ThreadPoolExecutor默认有四个拒绝策略:

1、ThreadPoolExecutor.AbortPolicy()   直接抛出异常RejectedExecutionException

2、ThreadPoolExecutor.CallerRunsPolicy()    直接调用run方法并且阻塞执行

3、ThreadPoolExecutor.DiscardPolicy()   直接丢弃后来的任务

4、ThreadPoolExecutor.DiscardOldestPolicy()  丢弃在队列中队首的任务

当然可以自己继承RejectedExecutionHandler来写拒绝策略.

int corePoolSize = 1;

int maximumPoolSize = 2;

int keepAliveTime = 10;

//BlockingQueue workQueue = new LinkedBlockingQueue();

BlockingQueue workQueue = new ArrayBlockingQueue(5);

ThreadFactory threadFactory = Executors.defaultThreadFactory();

//线程池和队列满了之后的处理方式

//1.跑出异常

RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

RejectedExecutionHandler handler2 = new ThreadPoolExecutor.CallerRunsPolicy();

RejectedExecutionHandler handler3 = new ThreadPoolExecutor.DiscardPolicy();

RejectedExecutionHandler handler4 = new ThreadPoolExecutor.DiscardOldestPolicy();

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, handler2);

for (int j = 1; j 

threadPoolExecutor.execute(new Runnable() {

public void run() {

try {

System.out.println(Thread.currentThread().getName());

TimeUnit.SECONDS.sleep(1);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});

}

System.out.println(threadPoolExecutor);

}

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

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

相关文章

yii1.0性能调优之改善并发数

开启YII的APC缓存 在config/main.php components 组件下添加&#xff1a; apccache>array(class>system.caching.CApcCache), 下载php_apc.dll&#xff0c;文件放到php/ext 下&#xff0c;搜索时可能会比较麻烦.... 在php.ini 中添加php_apc扩展&#xff1a; extension…

windows下apache报错The requested operation has failed解决方法

2019独角兽企业重金招聘Python工程师标准>>> Apache报错The requested operation has failed&#xff0c;基本上是因为端口被占用。解决方法如下&#xff1a; 第一步&#xff0c;运行cmd&#xff0c;cd 定位到Apache安装目录的bin目录下&#xff0c;输入httpd.exe -…

stm32 usmart使用

我直接用正点原子给的&#xff0c;步骤如下 先添加三个.c进工程&#xff0c;添加两个头文件的编译路径 #include "usart.h"#include "usmart.h" main函数里添加如下 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);// 设置中断优先级分组2 uart_init(960…

Scylla——开源免费的优秀代理 IP 池:自动验证、JSON API、基于 React 的 Web UI、Docker 支持...

GitHub&#xff1a;github.com/imWildCat/s… 中文文档&#xff1a;scylla.wildcat.io/zh/latest/ 自己是一个爬虫爱好者&#xff0c;有时候爬虫写的太过强大了被目标网站封了&#xff08;笑&#xff09;。所以就萌生了用代理 IP 的想法。很可惜很多开源代理 IP 池都是没有持续…

vs2015提示中文

解决方案&#xff1a;1.找到这个目录C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework 进入 \v4.0\zh-Hans的目录&#xff0c;全部复制&#xff0c;覆盖掉\v4.5\zh-Hans就行了

Istio 1.15 发布,支持 arm64 架构处理器

Istio 是基于容器的云原生技术栈的三大核心技术之一&#xff0c;另外两个是 Kubernetes 和 Knative。其中 Kubernetes 和 Knative 早已支持了 arm64 架构&#xff0c;甚至连 Istio 的数据平面 Envoy 早在 1.16 版本 [1] 就已支持 arm64 架构&#xff08;2020 年 10 月&#xff…

TP框架表单验证 【包含ajax方法】

之前的表单验证都是用js写的&#xff0c;这里也可以使用tp框架的验证。但是两者比较而言还是js验证比较好&#xff0c;因为tp框架验证会运行后台代码&#xff0c;这样运行速度和效率就会下降。  自动验证是ThinkPHP模型层提供的一种数据验证方法&#xff0c;可以在使用create创…

Spring 入门学习二之IOC

今天来学习Spring ioc .一、spring jar 包导入 在 spring 官网下载开发包 spring-framework-4.2.4.RELEASE,然后导入需要的 jar 包到项目 /lib/ 目录下。 &#xfffc; 二、代码开发 新建一个 src/cn/sxt/bean/Hello.java文件 package cn.sxt.bean;/*** Created by kaiyiwang o…

java 物理内存_聊聊Java中的内存

JVM的内存先放一张JVM的内存划分图&#xff0c;总体上可以分为堆和非堆(粗略划分&#xff0c;基于java8)那么一个Java进程最大占用的物理内存为&#xff1a;Max Memory eden survivor old String Constant Pool Code cache compressed class space Metaspace Thread st…

.Net CoreRabbitMQ基本使用

队列模式https://www.rabbitmq.com/getstarted.html对以上几种模式进行简要分类&#xff0c;可以分成如下三类(RPC暂不考虑)简单队列模式&#xff0c;单发单收&#xff0c;一对一模式Worker模式&#xff0c;单发多收(一个消息一个接收者&#xff0c;多个消息多个接收者)&#x…

【微信小程序】:实现轮播图3秒滚动

wxml模板&#xff1a;&#xff08;数据一维数组&#xff09; <scroll-view scroll-y"true"><swiper autoplay"auto" interval"3000" duration"500"><block wx:for"{{home_pics}}" wx:for-index"index…

Linux包系列的知识(附:Ubuntu16.04升级到18.04的案例)

Linux基础&#xff1a;https://www.cnblogs.com/dunitian/p/4822808.html#linux 之前看到朋友还动不动 apt-get update upgrade&#xff0c;就很纳闷&#xff0c;后来发现原来他只是知道这个更新命令却不知其意&#xff0c;所以每次安装个包就把所有apt-get的常用清除更新命令打…

java获取tomcat目录结构_Tomcat目录结构详解

Tomcat目录结构图如下&#xff1a;bin目录存放一些可执行的二进制文件&#xff0c;.sh结尾的为linux下执行命令&#xff0c;.bat结尾的为windows下执行命令。catalina.sh&#xff1a;真正启动tomcat文件&#xff0c;可以在里面设置jvm参数。startup.sh&#xff1a;启动tomcat(需…

智慧农业物联网云平台方案

2019独角兽企业重金招聘Python工程师标准>>> 多比智慧农业物联网云平台解决方案结合了最先进的物联网、云计算、传感器、自动控制等, 在浏览器或手机客户端实时显示大棚、大田、温室等温度、湿度、PH值、光强度、CO2&#xff0c;或作为自动控制的参变量参与到自动控…

Linux下汇编语言学习笔记65 ---

这是17年暑假学习Linux汇编语言的笔记记录&#xff0c;参考书目为清华大学出版社 Jeff Duntemann著 梁晓辉译《汇编语言基于Linux环境》的书&#xff0c;喜欢看原版书的同学可以看《Assembly Language Step-By-Setp:Programming with Linux 3rd Edition》&#xff0c;非常感谢该…

python:继承日志模块生成自定义日志

1 继承日志模块生成自定义日志 from __future__ import absolute_importimport os import sys import time import datetime import logging import logging.handlers import tempfileDATE_FORMAT %Y-%m-%d %H:%M:%Sdef create_logfile():if SYAPI_LOG_TEST in os.environ:val…

使用JDBC获取Oracle连接时报错

The Network Adapter could not establish the connection 网络适配器不能创建连接 作为初学者的来说&#xff0c;这个问题让我找了好多次&#xff0c;每次重新开启电脑时就可以正常获取连接&#xff0c;过了一会儿&#xff0c;自己不知道做了什么就会又报错&#xff0c;…

.Net CoreRabbitMQ消息转发可靠机制(上)

前言生产者发送消息到了队列&#xff0c;队列推送数据给了消费者&#xff0c;这里存在一些问题需要思考下生产者如何确保消息一定投递到了队列中RabbitMQ 丢失了消息(下文暂不涉及这块)队列如何确保消费者收到了消息呢生产者可靠发送执行流程当生产者将消息发送出去后&#xff…

堆栈的理解

Java把内存分成两种&#xff0c;一种叫做栈内存&#xff0c;一种叫做堆内存 在函数中定义的一些基本类型的变量和对象的引用变量都是在函数的栈内存中分配。当在一段代码块中定义一个变量时&#xff0c;java就在栈中为这个变量分配内存空间&#xff0c;当超过变量的作用域后&am…

MySQL安装时出现的问题

mysql正常安装结束之后需要连接你所安装的数据库的时候出现下面的错误: Client does not support authentication protocol requested by server;consider upgrading mysql client 解决方法:启动:mysql 8.0 command line client 之后输入下面的代码即可。use mysql;ALTER USER…