线程池Demo之
- ThreadPoolTaskExecutor
- import org.springframework.core.task.TaskExecutor;
- public class TaskExecutorExample {
- private TaskExecutor taskExecutor;
- public TaskExecutorExample(TaskExecutor taskExecutor) {
- this.taskExecutor = taskExecutor;
- }
- public void printMessages() {
- for(int i = 0; i < 25; i++) {
- taskExecutor.execute(new MessagePrinterTask("Message" + i));
- }
- }
- private class MessagePrinterTask implements Runnable {
- private String message;
- public MessagePrinterTask(String message) {
- this.message = message;
- }
- public void run() {
- System.out.println(message);
- }
- }
- }
- <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
- <property name="corePoolSize" value="5" />
- <property name="maxPoolSize" value="10" />
- <property name="queueCapacity" value="25" />
- </bean>
- <bean id="taskExecutorExample" class="powercn.TaskExecutorExample">
- <constructor-arg ref="taskExecutor" />
- </bean>
- ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
- long keepAliveTime, TimeUnit unit,
- BlockingQueue<Runnable> workQueue,
- RejectedExecutionHandler handler)
- corePoolSize: 线程池维护线程的最少数量
- maximumPoolSize:线程池维护线程的最大数量
- keepAliveTime: 线程池维护线程所允许的空闲时间
- unit: 线程池维护线程所允许的空闲时间的单位
- workQueue: 线程池所使用的缓冲队列
- handler: 线程池对拒绝任务的处理策略
- <bean id="taskExecutor"
- class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"
- scope="singleton" lazy-init="true">
- <property name="corePoolSize" value="${threadpool.corePoolSize}" />
- <property name="queueCapacity" value="${threadpool.queueCapacity}" />
- <property name="maxPoolSize" value="${threadpool.maxPoolSize}" />
- <property name="keepAliveSeconds" value="${threadpool.keepAliveSeconds}" />
- <property name="rejectedExecutionHandler">
- <bean class="${threadpool.rejectedExecutionHandler}" />
- </property>
- <!--作用是修改线程的名字-->
- <property name="threadNamePrefix" value="${threadpool.threadNamePrefix}" />
- </bean>
- threadpool.corePoolSize=5
- threadpool.queueCapacity=30
- threadpool.maxPoolSize=20
- threadpool.keepAliveSeconds=5
- threadpool.rejectedExecutionHandler=java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy
- threadpool.threadNamePrefix=myThread
- ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
- TaskExecutorExample te = (TaskExecutorExample)appContext.getBean("taskExecutorExample");
- te.printMessages();
- System.out.println("11111111111111111111111");