spring线程池管理

<!-- spring线程池 -->
    <bean id = "task" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
        <!-- 线程池维护线程的最少数量 -->
        <property name="corePoolSize" value="2"></property>
        <!-- 允许空闲时间 -->
        <property name="keepAliveSeconds" value="200"></property>
        <!-- 线程池维护线程的最大数量 -->
        <property name="maxPoolSize" value="5"></property>//配置为5,实际最大线程为maxPoolSize+1=6
        <!-- 缓存队列 -->
        <property name="queueCapacity" value="1"></property>
        <!-- 对拒绝task的处理策略 -->
        <property name="rejectedExecutionHandler">
             <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
        </property>
    </bean>

如下测试

@Controller
@RequestMapping("/")
public class index {
    @Autowired
    private TaskExecutor task;  //如上在spring配置文件中配置该线程池信息,名字要与配置文件中bean的id一样
    @RequestMapping(value = "/tx1", method = RequestMethod.GET)
    @ResponseBody
    public String tx1(){
        int i =0;
        while(i < 8){
            i++;
            task.execute(new Thread(){
                public void run() {
                    System.out.println("===="+index.this.hashCode()+"====="+Thread.currentThread().hashCode());
                    int a = 0;
                    while(a < 3){
                    try {
                        Thread.sleep(1000);
                        a++;
                        System.out.println(Thread.currentThread().hashCode()+":"+a);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }   
                    }
                    System.out.println(name+"==========结束==========");
                };
            });
        }       
        return "index";
    }
}

测试结果如下:同时进行的线程最大为6个线程,其它任务需要等线程处理完再进行

====261098527=====1258663477
====261098527=====2001246553
====261098527=====901774565
====261098527=====1542691695
====261098527=====1657056902
====261098527=====2038668338
1258663477:1
2038668338:1
1657056902:1
1542691695:1
901774565:1
2001246553:1
1258663477:2
2038668338:2
1657056902:2
1542691695:2
901774565:2
2001246553:2
1258663477:3
0==========结束==========
====261098527=====1258663477
2038668338:3
0==========结束==========
====261098527=====2038668338
1657056902:3
0==========结束==========
1542691695:3
0==========结束==========
901774565:3
0==========结束==========
2001246553:3
0==========结束==========
2038668338:1
1258663477:1
2038668338:2
1258663477:2
2038668338:3
0==========结束==========
1258663477:3
0==========结束==========
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值