spring线程池ThreadPoolExecutor配置并且得到任务执行的结果

简介:

spring线程池ThreadPoolExecutor配置并且得到任务执行的结果http://www.bieryun.com/1170.html

用的ThreadPoolExecutor的时候,又想知道被执行的任务的执行情况,这时就可以用FutureTask。

ThreadPoolTask

01 package com.zuidaima.threadpool;
02  
03 import java.io.Serializable;
04 import java.util.concurrent.Callable;
05  
06 public class ThreadPoolTask implements Callable<String>, Serializable {
07  
08     private static final long serialVersionUID = 0;
09  
10     // 保存任务所需要的数据
11     private Object threadPoolTaskData;
12  
13     private static int consumeTaskSleepTime = 2000;
14  
15     public ThreadPoolTask(Object tasks) {
16         this.threadPoolTaskData = tasks;
17     }
18  
19     public synchronized String call() throws Exception {
20         // 处理一个任务,这里的处理方式太简单了,仅仅是一个打印语句
21         System.out.println("开始执行任务:" + threadPoolTaskData);
22         String result = "";
23         // //便于观察,等待一段时间
24         try {
25             // long r = 5/0;
26             for (int i = 0; i < 100000000; i++) {
27  
28             }
29             result = "OK";
30         catch (Exception e) {
31             e.printStackTrace();
32             result = "ERROR";
33         }
34         threadPoolTaskData = null;
35         return result;
36     }
37 }

模拟客户端提交的线程

01 package com.zuidaima.threadpool;
02  
03 import java.util.concurrent.ExecutionException;
04 import java.util.concurrent.FutureTask;
05 import java.util.concurrent.TimeUnit;
06  
07 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
08  
09 public class StartTaskThread implements Runnable {
10  
11     private ThreadPoolTaskExecutor threadPoolTaskExecutor;
12     private int i;
13  
14     public StartTaskThread(ThreadPoolTaskExecutor threadPoolTaskExecutor, int i) {
15         this.threadPoolTaskExecutor = threadPoolTaskExecutor;
16         this.i = i;
17     }
18  
19     @Override
20     public synchronized void run() {
21         String task = "task@ " + i;
22         System.out.println("创建任务并提交到线程池中:" + task);
23         FutureTask<String> futureTask = new FutureTask<String>(
24                 new ThreadPoolTask(task));
25         threadPoolTaskExecutor.execute(futureTask);
26         // 在这里可以做别的任何事情
27         String result = null;
28         try {
29             // 取得结果,同时设置超时执行时间为1秒。同样可以用future.get(),不设置执行超时时间取得结果
30             result = futureTask.get(1000, TimeUnit.MILLISECONDS);
31         catch (InterruptedException e) {
32             futureTask.cancel(true);
33         catch (ExecutionException e) {
34             futureTask.cancel(true);
35         catch (Exception e) {
36             futureTask.cancel(true);
37             // 超时后,进行相应处理
38         finally {
39             System.out.println("task@" + i + ":result=" + result);
40         }
41  
42     }
43 }

SPRING配置文件

01 <?xml version="1.0" encoding="UTF-8"?>
02 <beans xmlns="http://www.springframework.org/schema/beans"
03     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
04     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
05     xsi:schemaLocation="
06         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
07         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
08         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
09         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
10         ">
11     <bean id="threadPoolTaskExecutor"
12         class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
13  
14         <!-- 核心线程数,默认为1 -->
15         <property name="corePoolSize" value="10" />
16  
17         <!-- 最大线程数,默认为Integer.MAX_VALUE -->
18         <property name="maxPoolSize" value="50" />
19  
20         <!-- 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE
21             <property name="queueCapacity" value="1000" /> -->
22  
23         <!-- 线程池维护线程所允许的空闲时间,默认为60s -->
24         <property name="keepAliveSeconds" value="300" />
25  
26         <!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 -->
27         <property name="rejectedExecutionHandler">
28             <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 -->
29             <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->
30             <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
31             <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->
32             <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
33         </property>
34     </bean>
35 </beans>

测试类

01 package com.zuidaima.test;
02  
03 import org.junit.Test;
04 import org.junit.runner.RunWith;
05 import org.springframework.beans.factory.annotation.Autowired;
06 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
07 import org.springframework.test.context.ContextConfiguration;
08 import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
09 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10  
11 import com.zuidaima.threadpool.StartTaskThread;
12  
13 @RunWith(SpringJUnit4ClassRunner.class)
14 // 指定的运行runner,并且把你所指定的Runner作为参数传递给它
15 @ContextConfiguration(locations = "classpath*:applicationContext.xml")
16 public class TestThreadPool extends AbstractJUnit4SpringContextTests {
17  
18     private static int produceTaskSleepTime = 10;
19  
20     private static int produceTaskMaxNumber = 1000;
21  
22     @Autowired
23     private ThreadPoolTaskExecutor threadPoolTaskExecutor;
24  
25     public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
26         return threadPoolTaskExecutor;
27     }
28  
29     public void setThreadPoolTaskExecutor(
30             ThreadPoolTaskExecutor threadPoolTaskExecutor) {
31         this.threadPoolTaskExecutor = threadPoolTaskExecutor;
32     }
33  
34     @Test
35     public void testThreadPoolExecutor() {
36         for (int i = 1; i <= produceTaskMaxNumber; i++) {
37             try {
38                 Thread.sleep(produceTaskSleepTime);
39             catch (InterruptedException e1) {
40                 e1.printStackTrace();
41             }
42             new Thread(new StartTaskThread(threadPoolTaskExecutor, i)).start();
43         }
44  
45     }
46  
47 }

原文中有些纰漏,我已经修改

项目截图(基于行家构建)

运行截图:

如果遇到CPU忙执行超过1秒的会返回空

相关文章
|
6月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
6月前
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
6月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
2196 0
|
8月前
|
Java Spring
Spring Boot配置的优先级?
在Spring Boot项目中,配置可通过配置文件和外部配置实现。支持的配置文件包括application.properties、application.yml和application.yaml,优先级依次降低。外部配置常用方式有Java系统属性(如-Dserver.port=9001)和命令行参数(如--server.port=10010),其中命令行参数优先级高于系统属性。整体优先级顺序为:命令行参数 &gt; Java系统属性 &gt; application.properties &gt; application.yml &gt; application.yaml。
1193 0
|
5月前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
6月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1108 5
|
6月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
338 0
探索Spring Boot的@Conditional注解的上下文配置
|
7月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
1297 10
|
8月前
|
人工智能 安全 Java
Spring Boot yml 配置敏感信息加密
本文介绍了如何在 Spring Boot 项目中使用 Jasypt 实现配置文件加密,包含添加依赖、配置密钥、生成加密值、在配置中使用加密值及验证步骤,并提供了注意事项,确保敏感信息的安全管理。
1447 1
|
8月前
|
SQL XML Java
配置Spring框架以连接SQL Server数据库
最后,需要集成Spring配置到应用中,这通常在 `main`方法或者Spring Boot的应用配置类中通过加载XML配置或使用注解来实现。
632 0

热门文章

最新文章