Spring线程池ThreadPoolTaskExecutor 的配置与使用

生成模型实战 | VQ-GAN(Vector Quantized-Generative Adversarial Network) 向量量化生成对抗网络 (Vector Quantized-Generative Adversarial Network, VQ-GAN) 结合了向量量化变分子自编码器 (VQ-VAE) 和生成对抗网络 (GAN) 的优势,通过向量量化 (Vector Quantised, VQ) 构建离散潜空间,结合感知损失与对抗损失,在保持语义一致性的同时能够生成纹理细节丰富的图像。在本节中,我们将详细解释 VQ-GAN 的技术原理和各个组成,并使用 PyTorch 从零开始实现 VQ-GAN。 阅读详情
AI摘要

本文介绍了如何在Spring中配置和使用ThreadPoolTaskExecutor线程池。内容包括线程池的配置,通过注入线程池相关配置,创建实现Runnable接口的自定义线程类,并在代码中优化线程管理,以防止线程数超过限制引发错误。

有关Java线程池,可参见csdn线程池

线程池的配置
<!-- 异步线程池 -->
    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 核心线程数  -->
        <property name="corePoolSize" value="10"/>
        <!-- 最大线程数 -->
        <property name="maxPoolSize" value="200"/>
        <!-- 队列最大长度 >=mainExecutor.maxSize -->
        <property name="queueCapacity" value="10"/>
        <!-- 线程池维护线程所允许的空闲时间 -->
        <property name="keepAliveSeconds" value="20"/>
        <!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
        </property>
    </bean>
线程池的使用
注入线程池的相关配置
@Resource(name="taskExecutor")
ThreadPoolTaskExecutor taskExecutor;
// 或者可以直接@Autowried
@AutoWired
ThreadPoolTaskExecutor taskExecutor;

注意,再自动注入并创建ThreadPoolTaskExecutor的一个对象时,会执行ThreadPoolTaskExecutor.initialize()方法进行初始化

创建一个实现Runnable接口的自定义线程类
package cn.test.utils;
import org.apache.commons.collections.CollectionUtils;
import java.util.List;
public class RuleThread implements Runnable {
   	// 自定义类的属性及getset方法,用来传输数据
    private String name;
    private List<String> idList;
    public List<String> getIdList() {
        return idList;
    }

    public void setIdList(List<String> idList) {
        this.idList = idList;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    // run方法
    @Override
    public void run() {
        excute();
    }
    private void excute() {
        // 编写要执行的业务方法
    }
}

创建自定义线程类对象并调用spring线程池去管理线程
// 初始化线程池
taskExecutor.initialize();
// 创建自定义对象并赋值属性
RuleThread ruleThread = new RuleThread();
ruleThread.setName("当前线程名");
ruleThread.setIdList(new ArrayList());
// 执行线程
taskExecutor.execute(ruleThread);
// 销毁线程池
taskExecutor.destroy();
为防止线程数超过限制报错,优化上面代码如下
// 初始化线程池
taskExecutor.initialize();
for(int i=1;i<10;i++){
    while(true){
        // 创建自定义对象并赋值属性
        RuleThread ruleThread = new RuleThread();
        ruleThread.setName("当前线程名");
        ruleThread.setIdList(new ArrayList());
        // 执行线程
        taskExecutor.execute(ruleThread);
        break;
    }
}
// 销毁线程池
taskExecutor.destroy();
半导体材料仿真:二维材料仿真_(1).二维材料的基本概念 在半导体材料仿真领域,二维材料因其独特的物理和化学性质而受到广泛关注。二维材料,也称为二维纳米材料,是指在二维空间(通常是平面)上具有原子级厚度的材料。这些材料的厚度通常在几个纳米甚至单个原子层的范围内,使得它们在电子、光学、热学和机械性能上表现出与传统三维材料显著不同的特性。本节将详细介绍二维材料的基本概念,包括它们的分类、结构、性质以及在半导体材料仿真中的应用。 阅读详情

相关推荐

【论文导读】ICDM2018|SASRec---基于自注意力机制的序列推荐(召回)

前言本次分享2018年发表在ICDM上的论文----「Self-Attentive Sequential Recommendation」。主要是应用self-attention机制来做一...

Blank_Space 8033

浅谈线程池

一.线程池的作用: 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行 提高线程的可管理性,线程是稀缺资源,如果无限制地创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一分配、调优和监控 二.java线程池ThreadPoolExecutor类使用详解: 在《阿里巴巴java...

answer94的博客 1116

基于知识图谱的职位推荐系统的设计与实现

在职位推荐系统中,实体可以包括职位、公司、技能等,而关系可以包括职位与公司的关联、职位与技能的关联等。基于知识图谱的职位推荐系统可以提供更加智能和精确的职位推荐服务。通过收集和预处理数据构建知识图谱,并设计推荐算法和用户界面,可以实现一个完整的职位推荐系统。通过利用知识图谱技术,我们可以构建一个更加智能和精确的职位推荐系统。本文将介绍如何设计和实现基于知识图谱的职位推荐系统,并提供相应的源代码。通过定义实体和关系的节点和边,可以将数据存储在图数据库中,并建立它们之间的关系。

RiqaEditor的博客 1668

Spring Boot线程池使用

前言 前两天做项目的时候,想提高一下插入表的性能优化,因为是两张表,先插旧的表,紧接着插新的表,一万多条数据就有点慢了 后面就想到了线程池ThreadPoolExecutor,而用的是Spring Boot项目,可以用Spring提供的对ThreadPoolExecutor封装的线程池ThreadPoolTaskExecutor,直接使用注解启用 使用步骤 先创建一个线程池的配置,让Spring Boot加载,用来定义如何创建一个ThreadPoolTaskExecutor,要使用@Config

剑雪封喉 782

傅里叶光学(1)

傅里叶光学,可以看作是通信理论中傅里叶变换等一系列数学思想以及系统理论与光学(主要是衍射光学)相结合的产物关于傅里叶光学的应用领域,本节介绍了成像,当然事实上不可能仅限于成像,经典的还如激光散斑的一些应用,干涉计量,还有傅里叶变换光谱学等等。最后总结一下,傅里叶光学我认为可以看做一个工具,对于任意的系统,它能给出一些数学思想与物理原理进行解释和分析,找出系统的扰动和响应的关系,或者说根据扰动和响应,来研究或者设计一个系统。

m0_53607446的博客 1670

给STM32F103的7寸屏找个新UI:LVGL 8.2裸机移植保姆级教程(附避坑清单)

本文详细介绍了如何将LVGL 8.2裸机移植到STM32F103开发板,特别针对7寸大屏(800×480分辨率)进行优化配置。从环境准备、工程搭建到显示驱动移植、内存优化与性能调优,提供完整的解决方案和避坑清单,帮助开发者快速实现美观的用户界面。

weixin_29181861的博客 413

Spring多线程之TaskExecutor

一般来说,任务执行都是同步的、 Spring通过TaskExecutor来实现多线程,异步执行,通过注解@EnableAsync来开启异步任务执行的支持  下面进行测试: 一、新建一个maven项目,并导入spring的包 &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;a...

fantasic_van的博客 4168

量化投资从0开始系列 ---- 15. 郑商所日统计数据

前面已经提取了其它期货交易所的数据,最后还剩下郑商所。相比而言,郑商所的数据获取比其它几个交易所更麻烦一点。因为郑商所的系统接口有两个,在2015年11月11日前后发生了切换,这个日期之前是老系统的api接口,这个日期之后是一个新的api接口。 具体的地址在哪里,还是依靠在浏览器中按F12来确定,最后发现的地址是: if trade_date > '20151111': czce_url = f'http://www.czce.com.cn/cn/DFSS

kengxie的博客 2112

Java线程池

在目前我们常用的springboot项目中。我们一般会将线程池交由spring进行管理: @EnableAsync @Component public class AsyncThreadPool { @Bean public ThreadPoolTaskExecutor initializeThreadPool() { ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor (); ..

weixin_47996698的博客 756

【OpenSearch】从零到一:手把手搭建OpenSearch与Dashboard可视化平台

本文提供了一份详细的OpenSearch与Dashboard可视化平台从零搭建指南。内容涵盖环境准备、系统调优、核心服务安装配置、Dashboard部署与汉化,以及生产环境安全加固建议,帮助用户快速构建一个功能完整的搜索与分析平台。

devops8pract的博客 617

C++ int转四字节数组

字节转换

我不是码农的博客~~~ 973

java多线程实现方式(四)

hello,伙伴们,我们继续java多线程实现方式的学习,本节中我们通过线程池来实现多线程。那为什么使用线程池呢?使用线程池的好处是减少在创建和销毁线程上所花的时间以及系统资源的开销,解决资源不足的问题。如果不使用线程池,有可能造成系统创建大量同类线程而导致消耗完内存或者 “过度切换”的问题。在阿里开发手册中明确线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样 的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。那么我们接下来创...

hardworking_Man的博客 894

C# 与欧姆龙 PLC 实战:通过 Ethernet/IP 协议进行设备控制与监控

本文介绍了如何通过C#和Ethernet/IP协议实现与欧姆龙PLC的通信。Ethernet/IP是基于以太网的工业协议,适用于工业设备间的实时数据交换。文章详细讲解了使用EthernetIPSharp库建立连接、读写数据的步骤,并提供了示例代码。此外,还探讨了实时监控、报警系统等高级功能,为工业自动化控制系统开发提供了实用指导。该方法简化了PLC通信开发,提高了系统可靠性和智能化程度。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 811

Spring线程池的配置及使用ThreadPoolTaskExecutor

Spring线程池的配置及使用ThreadPoolTaskExecutor前言一、ThreadPoolTaskExecutor是什么?二、代码实现1.配置类ExecutorConfig2.引入使用总结 提示:以下是本篇文章正文内容,下面案例可供参考 一、ThreadPoolTaskExecutor是什么? ThreadPoolTaskExecutor是Spring提供的线程池,通过配置参数初始化线程池,随取随用,不需要创建和销毁。

wjs970410888的博客 5926

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

深度学习工具包 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")

Spring线程池ThreadPoolTaskExecutor配置与实践

ThreadPoolTaskExecutor是Spring框架提供的线程池实现,继承自Java标准库的ThreadPoolExecutor,专为Spring应用优化,支持更灵活的配置和集成。本文将系统梳理其核心功能、配置参数、使用示例及避坑指南。

xiaoyaozizai1的博客 970

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

spring中使用ThreadPoolTaskExecutor配置线程池

软件工程实践没有银弹, 一切都要结合实际场景去考虑。

qq_38593205的博客 3620

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

java 线程池(ExecutorService与Spring配置threadPoolTaskExecutor)

一、java ExecutorService实现 创建ExecutorService变量 private ExecutorService executor = null       2.执行对应任务时,首先生成线程池 executor = Executors.newFixedThreadPool(线程池大小);       3.循环执行线程         fo

kai763253075的博客 1万+

Spring线程池ThreadPoolTaskExecutor配置及详情

&lt;!-- spring thread pool executor --&gt; &lt;bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"&gt; &lt;!-- 线程池维护线程的最少数量 --&gt; ...

chenpeng19910926的专栏 4555

java spring 线程池_Spring线程池ThreadPoolTaskExecutor配置及详情

Spring线程池ThreadPoolTaskExecutor配置及详情1. ThreadPoolTaskExecutor配置1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

weixin_39638468的博客 211

Spring框架使用xml方式配置ThreadPoolTaskExecutor线程池,并且自定义线程工厂

自定义线程工厂需要实现接口,重写newThread方法。import org/*** 业务自定义线程工程// 线程组 private final ThreadGroup group;// 线程序号 private final AtomicInteger threadNumber = new AtomicInteger(1);// 线程名称前缀 private final String namePrefix;= null?

qq_39464523的博客 1361

java executor spring_java 线程池(ExecutorService与Spring配置threadPoolTaskExecutor)

一、java ExecutorService实现创建ExecutorService变量private ExecutorService executor = null2.执行对应任务时,首先生成线程池executor = Executors.newFixedThreadPool(线程池大小);3.循环执行线程for (String str : ids) {executor.submit(new Ca...

weixin_35719380的博客 307

Spring线程池ThreadPoolTaskExecutor的配置和使用

//1.搭建个简单的springmvc框架框架结构 2.applicationContext配置 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.or...

weixin_30616969的博客 456
上一篇: Maven生命周期等简述
下一篇: Jquery简述——write less do more
hynkoala
博客等级 码龄10年 8粉丝 26原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值