跳至主要內容

springmvc线程池

chanchaw小于 1 分钟javaspring

配置文件设置bean

springmvc 项目的配置文件 spring-context.xml 中添加下面 bean 设置

    <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 线程池维护线程的最少数量 -->
        <property name="corePoolSize" value="2" />
        <!-- 线程池维护线程的最大数量 -->
        <property name="maxPoolSize" value="1000" />
        <!-- 线程池所使用的缓冲队列 -->
        <property name="queueCapacity" value="200" />
        <!-- 线程池维护线程所允许的空闲时间 -->
        <property name="keepAliveSeconds" value="2000" />
        <property name="rejectedExecutionHandler">
            <bean class="java.util.concurrent.ThreadPoolExecutor$AbortPolicy" />
        </property>
    </bean>

依赖注入并使用

@Resource
private TaskExecutor taskExecutor;

@RequestMapping(value = "/testTaskExecutor", method = RequestMethod.GET)
public JsonResult testTaskExecutor () throws InterruptedException {
    System.out.println(DateUtil.getFormatDate(new Date(),"yyyy-MM-dd HH:mm:ss.SSS - ") + "进入接口");
    taskExecutor.execute(() -> {
        System.out.println(DateUtil.getFormatDate(new Date(),"yyyy-MM-dd HH:mm:ss.SSS - ") + "进入子线程");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(DateUtil.getFormatDate(new Date(),"yyyy-MM-dd HH:mm:ss.SSS - ") + "子线程执行完毕");
    });
    Thread.sleep(2000);
    System.out.println(DateUtil.getFormatDate(new Date(),"yyyy-MM-dd HH:mm:ss.SSS - ") + "接口执行完毕");
    return JsonResult.ok("API testTaskExecutor 执行完毕!");
}