话不多说直接上步骤
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注解实现线程池)