• spring 配置 线程池并使用 springtest 进行测试


    在 applicationContext.xml 中配置spring线程池:

        <!-- 包路径扫描 -->
        <context:component-scan base-package="spring.task"/>
    
        <!-- Spring线程池 -->
        <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
            <!-- 核心线程数 -->
            <property name="corePoolSize" value="5" />
            <!-- 线程池维护线程的最大数量 -->
            <property name="maxPoolSize" value="10" />
            <!-- 允许的空闲时间, 默认60秒 -->
            <property name="keepAliveSeconds" value="60" />
            <!-- 任务队列 -->
            <property name="queueCapacity" value="50" />
            <!-- 线程超过空闲时间限制,均会退出直到线程数量为0 -->
            <property name="allowCoreThreadTimeOut" value="true"/>
            <!-- 对拒绝task的处理策略 -->
            <property name="rejectedExecutionHandler">
                <bean class="java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy" />
            </property>
        </bean>
    当一个新任务来临时:
    1)如果此时线程池中的数量小于corePoolSize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务;
    2)如果此时线程池中的数量等于corePoolSize,但是缓冲队列workQueue未满,那么任务被放入缓冲队列;
    3)如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量小于maxPoolSize,建新的线程来处理被添加的任务;
    4)如果此时线程池中的数量大于corePoolSize,缓冲队列workQueue满,并且线程池中的数量等于maxPoolSize,那么通过handler所指定的策略来处理此任务;
    5)当线程池中的线程数量大于corePoolSize时,如果某线程空闲时间超过keepAliveTime,线程将被终止,如果allowCoreThreadTimeOut为false,则线程数量维持在corePoolSize, 如果为true,则线程数量可最低降至0;

    下面是 springtest 的实现方式:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class AsyncTask {
    
        @Autowired
        private ThreadPoolTaskExecutor executor;
    
    //    @PostConstruct 注解需要使用,否则不能成功看到输出(这里说的是在springtest里,在项目中使用不加这个,否则会报错)
        @PostConstruct
        public void testAsycTask() {
            for (int i = 0; i < 10; i++) {
                executor.execute(new Runnable() {
                    public void run() {
                        asyncTask();
                    }
                });
            }
        }
    
    //    这里需要设置为 public
        @Test
        public void asyncTask() {
            System.out.println("---" + Thread.currentThread().getName());
        }
    }

    成功:

     springmvc 每一个请求都会自动使用一个独立的线程来进行处理

  • 相关阅读:
    苹果的HomeKit协议
    广州出游计划
    Qt学习博客推荐
    Log4Qt使用(三)在DailyRollingFileAppender类中增加属性mMaxBackupIndex
    QT中关于窗口全屏显示与退出全屏的实现
    键盘事件-----按下回车键则触发事件
    窗体显示/编码设置/开机启动/文件选择与复制/对话框等
    设置系统日期时间
    输入内容, 列出可选的项: QComboBox
    如何根据安装时缺失的文件查找对应的包
  • 原文地址:https://www.cnblogs.com/kinome/p/10251299.html
Copyright © 2020-2023  润新知