spring(用ThreadPoolTaskExecutor简单实现线程池)

话不多说直接上步骤
1.在spring.xml配置线程池bean

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<!-- 核心线程数 -->
		<property name="corePoolSize" value="4" />
		<!-- 最大线程数 -->
		<property name="maxPoolSize" value="20" />
		<!-- 队列最大长度 -->
		<property name="queueCapacity" value="20" />
		<!-- 线程池维护线程所允许的空闲时间,默认为60s -->
		<property name="keepAliveSeconds" value="60" />
	</bean>

2.在需要使用多线程的类中注入线程池bean,就可以使用了,下面代码是本人写的一个测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class ThreadTest {

    @Autowired
    private TaskExecutor taskExecutor;

    @Test
    public void testThread(){
        taskExecutor.execute(new Runnable() {
            public void run() {
                for(int i=0;i<10;i++){
                    try {
                        System.out.println("线程:"+i);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        for(int i=0;i<10;i++){
            try {
                System.out.println("非线程:"+i);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

结果如图

结果图

当然还有更加简便的实现多线程的方法,可以参考博主的另一篇博客:Spring(@Async注解实现线程池)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值