1.初始化ThreadPoolTaskExecutor
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 線程池維護線程的最少數量 -->
<property name="corePoolSize" value="5" />
<!-- 允許的空閒時間 -->
<property name="keepAliveSeconds" value="200" />
<!-- 線程池維護線程的最大數量 -->
<property name="maxPoolSize" value="10" />
<!-- 緩存隊列 -->
<property name="queueCapacity" value="20" />
<!-- 對拒絕task的處理策略 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
</bean>
2.定義多線程Demo
/**
* 多線程併發處理demo
* @author daniel.zhao
*
*/
public class MultiThreadDemo implements Runnable {
private MultiThreadProcessService multiThreadProcessService;
public MultiThreadDemo() {
}
public MultiThreadDemo(MultiThreadProcessService multiThreadProcessService) {
this.multiThreadProcessService = multiThreadProcessService;
}
@Override
public void run() {
multiThreadProcessService.processSomething();
}
}
3.將線程放入線程池
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MultiThreadConfig.class })
public class MultiThreadTest {
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
private MultiThreadProcessService multiThreadProcessService;
@Test
public void test() {
int n = 20;
for (int i = 0; i < n; i++) {
taskExecutor.execute(new MultiThreadDemo(multiThreadProcessService));
System.out.println("int i is " + i + ", now threadpool active threads totalnum is " + taskExecutor.getActiveCount());
}
try {
System.in.read();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}