ThreadPoolExecutor的应用

线程池ThreadPoolExecutor的实现原理解析及实际应用场景 ThreadPoolExecutor适用于需要处理大量并发任务的场景,如: 电商系统:电商系统在高峰期需要处理大量的用户请求,使用线程池可以有效地管理和调度线程,提高系统的吞吐量。 游戏服务后端框架:游戏服务器需要处理大量的用户操作,如移动、攻击等。使用线程池可以提高游戏的响应速度和性能。 网约车:网约车系统需要处理大量的订单请求和司机调度。使用线程池可以优化系统的并发性能,提高订单的处理速度。 社交平台:社交平台需要处理大量的用户活动,如发帖、评论、点赞等。 阅读详情

ThreadPoolExecutor是阿里推荐的线程池。可以控制线程的数量、队列的大小等。

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
    }
corePoolSize: 核心线程的数量。
maximumPoolSize: 线程池最大的数量。
keepAliveTime: 空闲线程结束的超时时间(当一个线程不工作时,过keepAliveTime 长时间将停止该线程)。
unit: 表示keepAliveTime的单位。
workQueue: 放任务的队列


workQueue: 有三种类型
LinkedBlockingQueue: 链表的形式存储队列。
ArrayBlockingQueue: 数组的形式存储队列。
SynchronousQueue: 同步阻塞队列。

三者都是继承了BlockingQueue。

使用BlockingQueue最大的问题应该是StackOverflowError。
主要是涉及到了如何调节corePoolSize、maximumPoolSize、workQueue.capacity的值。

队列中最大的线程数 = maximumPoolSize + workQueue.capacity

例如:
 

ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(5, true);
ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 4, 1L, TimeUnit.SECONDS, workQueue);

List<Integer> iArray = new ArrayList<>();
for (Integer i = 0; i < 9; i++) {
    executor.submit(new Runnable() {
        @Override
        public void run() {
            System.out.println("thread-id:" + Thread.currentThread().getId());
        }
    });
}

workQueue队列中最大的数量应该是 4 + 5 = 9.

线程创建规则:
线程先运行: thread-id:0, thread-id:1, thread-id:2
压入队列: thread-id:3, thread-id:4, thread-id:5, thread-id:6, thread-id:7
在调用线程运行: thread-id:8


先执行3个线程,然后在把后面的压入队列,如果队列满后,就再次创建线程。最大线程数量不超过maximumPoolSize,否则就会报错。

[QMT和ptrade量化交易小白入门]-112、小市值热点概念交易策略,回测5年20倍 本专栏主要是介绍QMT和ptrade的基础用法,常见函数,写策略的方法,也会分享一些量化交易的思路,大概会写200篇左右。QMT的相关资料较少,在使用过程中不断的摸索,遇到了一些问题,记录下来和大家一起沟通,共同进步。 阅读详情

相关推荐

经典烧脑算法逻辑题--高楼扔鸡蛋:最少次数测出鸡蛋摔碎临界点。

如果在第2层没碎,换到第3层扔.......如果第59层没碎,换到第60层扔;有2个鸡蛋,从100层楼上往下扔,以此来测试鸡蛋的硬度。比如鸡蛋在第9层没有摔碎,在第10层摔碎了,那么鸡蛋不会摔碎的临界点就是9层。因此,我们尝试每10层扔一次,第一次从10层扔,第二次从20层扔,第三次从30层......一直扔到100层。如果第一枚鸡蛋,在50层碎了,第二枚鸡蛋,就从第1层开始扔,一层一层增长,一直扔到第49层。如果第一枚鸡蛋在50层没碎了,则继续使用二分法,在剩余楼层的一半(75层)往下扔。

借雨醉东风的博客 1817

线程池的使用(ThreadPoolExecutor详解)

为什么要使用线程池? 线程是一个操作系统概念。操作系统负责这个线程的创建、挂起、运行、阻塞和终结操作。而操作系统创建线程、切换线程状态、终结线程都要进行CPU调度——这是一个耗费时间和系统资源的事情。&nbsp; 另一方面,大多数实际场景中是这样的:处理某一次请求的时间是非常短暂的,但是请求数量是巨大的。这种技术背景下,如果我们为每一个请求都单独创建一个线程,那么物理机的所有资源基本上都被操作系统...

cjg_2015的博客 295

Vivado与VCS+Verdi联合仿真环境搭建全攻略

本文详细介绍了如何搭建Vivado与VCS+Verdi联合仿真环境,旨在解决Vivado Simulator在大型FPGA验证中速度慢、调试弱的问题。通过指导工具版本配对、环境变量设置、关键参数配置及Xilinx仿真库编译,帮助工程师高效整合Vivado的设计管理、VCS的高速仿真与Verdi的深度调试能力,从而显著提升验证效率。

weixin_29219189的博客 576

线程池ThreadPoolExecutor 的使用

由于该队列的近似无界性,当线程池中线程数量达到corePoolSize后,再有新任务进来,会一直存入该队列,而不会去创建新线程直到maxPoolSize,因此使用该工作队列时,参数maxPoolSize其实是不起作用的。也就是说新任务进来时,不会缓存,而是直接被调度执行该任务,如果没有可用线程,则创建新线程,如果线程数量达到maxPoolSize,则执行拒绝策略。:创建线程的工厂类,通常我们会自定义一个threadFactory设置线程的名称,这样我们就可以知道线程是由哪个工厂类创建的,可以快速定位。

qishiheyongshi的专栏 2285

避开CPU瓶颈:手把手教你用RK3588的DMA-BUF实现V4L2到NPU的零拷贝数据流

本文详细介绍了如何在RK3588平台上利用DMA-BUF实现V4L2到NPU的零拷贝数据流,显著提升异构计算性能。通过实战指南展示了如何配置摄像头采集、RGA图像预处理和NPU推理优化,最终实现CPU占用率降低60%、延迟减少60%的效果,特别适合YOLOv5等AI推理应用的高效部署。

weixin_30374009的博客 571

【鸿蒙实战开发】HarmonyOS申请调试签名证书过程

这份鸿蒙(HarmonyOS NEXT)资料包含了鸿蒙开发必掌握的核心知识要点,内容包含了(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)技术知识点。

HarmonyOS_002的博客 3560

ThreadPoolExcutor

2、线程池的创建 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ..

weixin_42258334的博客 8068

Allegro规则管理器实战:5步搞定Xnet等长组设置(含Relative Propagation Delay配置)

本文详细介绍了在Cadence Allegro规则管理器中,通过5个实战步骤高效设置Xnet等长组的方法。核心内容包括创建Xnet属性、定义引脚对、建立匹配组,并重点讲解了Relative Propagation Delay规则的配置与应用,帮助PCB设计师确保高速信号时序对齐,提升系统稳定性与性能。

weixin_29193259的博客 514

ThreadPoolExecutor详解

一、ThreadPoolExecutor类讲解 1、线程池状态: 五种状态: 线程池的状态 说明 RUNNING 允许提交并处理任务 SHUTDOWN 不允许提交新的任务,但是会处理完已提交的任务 STOP 不允许提交新的任务,也不会处理阻塞队列中未执行的任务, 并设置正在执行的线程的中断标志位 TIDYING .

赶路人儿 11万+

Flask基础项目:从零到一搭建用户管理系统

本文介绍了一个基于Flask的用户管理系统,具有完整的增删改查功能。系统采用SQLAlchemy ORM进行数据库操作,自动处理SQL注入并首次运行时创建表结构。主要特点包括:实时统计用户总数和平均年龄、智能即时搜索、前后端双重数据验证、邮箱唯一性检查、流畅动画效果和响应式设计。后端使用Flask框架实现RESTful API,前端采用现代化UI设计,支持异步操作不阻塞界面。系统安装简单,只需创建数据库并安装依赖即可运行,适合作为基础用户管理系统的参考实现。

数据知道的博客 3837

制作INCA和CANape通用的A2L

CANape和INCA通用的A2L配置与修改

赞的博客 5960

线程池ThreadPoolExecutor的使用

一、手动创建线程的缺点: (1)创建多个线程,会消耗许多内存。 (2)创建多个线程,也非常耗时。 (3)最重要的是,频繁创建线程,在任务执行完毕之后被回收,对GC也有一定的压力。 二、线程池 线程池:创建线程变成了从线程池获取空闲的线程,关闭线程变成了向池子中归还线程。 合理地使用线程池能够带来三个好处: ......

大宇的博客,欢迎访问 2万+

手把手教你学simulink实例--基于Simulink的船舶发电柴油机建模与健康状态研究

船舶发电柴油机是现代船舶电力系统的核心设备,为船舶提供稳定的电能供应。然而,由于长期运行在复杂的海洋环境中,船舶发电柴油机容易受到磨损、腐蚀和疲劳等损伤的影响,导致其性能下降甚至发生故障。因此,对船舶发电柴油机进行建模和健康状态监测具有重要意义。本项目旨在使用MATLAB/Simulink平台,建立船舶发电柴油机的动力学模型,并通过仿真分析其健康状态,预测潜在故障,从而提高船舶运行的安全性和经济性。

MHD0815的博客 1323

【线程池】ThreadPoolExecutor应用

ThreadPoolExecutor的应用,介绍相关的使用此线程池的核心参数以及涉及的必须掌握知识,详细介绍其中一共提供了7个参数,每个参数都是核心的属性,在线程池执行任务时,每个参数都有决定性的作用在使用JDK提供的方式去构建,可以设置的核心参数最多就2个,这样会导致我们对线程池的控制粒度很粗所以在阿里的规范中,亦是推荐我们手动的去new一个线程池,并设置他的核心属性自定义的好处可以细粒度的控制线程池,管理内部的属性并针对一些参数的设置可能更好的在后期排查问题。

aristo 634

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

线程池ThreadPoolExecutor应用

一个老生常谈的问题:线程的创建及销毁是非常消耗时间及资源的。 ThreadPoolExecutor ThreadPoolExecutor提供了很多构造方法,这里主要说以下这个,其他构造方法都是基于此方法: public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,

好记性不如烂笔头 1231

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

ThreadPoolExecutor的例子与应用方式

JDK1.5中的线程池(java.util.concurrent.ThreadPoolExecutor)使用简介java 2009-11-26 11:26:16 阅读60 评论0 字号:大中小 在多线程大师Doug Lea的贡献下,在JDK1.5中加入了许多对并发特性的支持,例如:线程池。 一、简介 线程池类为 java.util.concurrent.ThreadPoolExecuto

xtwolf008--关注分布式存储,关注大数据,云计算PAAS 6027

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ThreadPoolExecutor 简单应用

适用场景:读取数据库数据,刷数据等批量操作 直接上代码 package test; import com.alibaba.fastjson.JSONObject; import io.tava.function.Consumer1; import org.springframework.stereotype.Component; @Component public class Producers implements Consumer1<JSONObject>{ private

我思故我在 551

AbstractQueuedSynchronizer(十五)——应用之ThreadPoolExecutor

todo

xxcupid的博客 359

ThreadPoolExecutor应用&源码剖析(一)

首先ThreadPoolExecutor中,一共提供了7个参数,每个参数都是非常核心的属性,在线程池去执行任务时,每个参数都有决定性的作用。但是如果直接采用JDK提供的方式去构建,可以设置的核心参数最多就两个,这样就会导致对线程池的控制粒度很粗。所以在阿里规范中也推荐自己去自定义线程池。手动的去newThreadPoolExecutor设置他的一些核心属性。自定义构建线程池,可以细粒度的控制线程池,去管理内存的属性,并且针对一些参数的设置可能更好的在后期排查问题。

qq_45309297的博客 1862

ThreadPoolExecutor应用

ThreadPoolExecutor JDK能够提供的线程池, 大家可以往这个线程池里面扔东西,让它自己去运行,首先看戏如何定义一个线程池: 这里面有7个 参数: public ThreadPoolExecutor( int corePoolSize, 核心线程数 int maximumPoolSize, 最大线程数 long keepAliveTime, 生存时间,线程多久没干活请归还操作系统 TimeUnit unit,生存时间的单位 BlockingQueue workQueue, 任务队列 Thre

yanfei464486的博客 229

ThreadPoolExecutor + CountDownLatch 实际应用

ThreadPoolExecutor + CountDownLatch 实际应用 Java并发编程笔记之 CountDownLatch闭锁的源码分析 线程池之ThreadPoolExecutor使用

ZPHTTT的博客 912

ThreadPoolExecutor和Callable的应用

一、Responsepublic class Response&lt;T&gt; implements Serializable { private String key; private T response; public Response(String key, T response) { this.key = key; ...

帅性而为1号的博客 2160

ThreadPoolExecutor策略配置以及应用场景

ThreadPoolExecutor策略配置以及应用场景 ThreadPoolExecutor 是用来处理异步任务的一个接口,可以将其理解成为一个线程池和一个任务队列,提交到 ...

TuxedoLinux的博客 238

应用线程池ThreadPoolExecutor

在配置和调整应用线程池的时候,首先考虑的是线程池的大小。 线程池的合理大小取决于未来提交的任务类型和所部署系统的特征。定制线程池的时候需要避免线程池的长度“过大”或者“过小”这两种极端情况。 线程池过大:那么线程对稀缺的CPU和内存资源的竞争,会导致内存高使用量,还可能耗尽资源。 线程池过小:由于存在很多可用的处理器资源还未工作,会对吞吐量造成损失。 精密的计算出线程池的确切大小是很困难的,一般我们会估算出一个合理的线程池大小。

DR的专栏 2356

ThreadPoolExecutor线程池源码解析与应用分析

ThreadPoolExecutor线程池源码解析与应用分析

qq_41490913的博客 96
上一篇: 服务器的并发数
下一篇: RabbitMQ控制台详解
think12
博客等级 码龄17年 132粉丝 173原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值