实现类
1 import org.springframework.core.task.TaskExecutor; 2 3 public class DemoBOImpl 4 { 5 // 线程池 6 @Resource(name = "taskExecutor") 7 private TaskExecutor taskExecutor; 8 9 @Override 10 public void executeThread() throws Exception { 11 // 线程池控制 12 taskExecutor.execute(new DemoThread()); 13 } 14 }
线程类
1 public class DemoThread implements Runnable 2 { 3 public DemoThread() { 4 } 5 6 @Override 7 public void run() { 8 try { 9 // do things 10 } catch (Exception e) { 11 } 12 } 13 }
Spring配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" 7 xsi:schemaLocation=" http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 9 http://www.springframework.org/schema/aop 10 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 13 http://www.springframework.org/schema/context 14 http://www.springframework.org/schema/context/spring-context-2.5.xsd 15 http://www.springframework.org/schema/jee 16 http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"> 17 18 <context:annotation-config /> 19 20 <!-- Spring线程池配置开始 --> 21 <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> 22 <!-- 核心线程数,默认为1 --> 23 <property name="corePoolSize" value="1" /> 24 <!-- 最大线程数,默认为Integer.MAX_VALUE --> 25 <property name="maxPoolSize" value="1" /> 26 <!-- 队列最大长度,默认为Integer.MAX_VALUE --> 27 <property name="queueCapacity" value="1" /> 28 <!-- 线程池维护线程所允许的空闲时间,默认为60s --> 29 <property name="keepAliveSeconds" value="60" /> 30 <!-- 线程池对拒绝任务(无线程可用)的处理策略,目前只支持AbortPolicy、CallerRunsPolicy;默认为后者 --> 31 <property name="rejectedExecutionHandler"> 32 <!-- AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常 --> 33 <!-- CallerRunsPolicy:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 --> 34 <!-- DiscardOldestPolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 --> 35 <!-- DiscardPolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 --> 36 <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /> 37 </property> 38 </bean> 39 <!-- Spring线程池配置结束 --> 40 </beans>
时间: 2024-10-11 12:04:17