spring ThreadPoolTaskExecutor的线程池类实现多线程

来源:互联网 发布:万网域名交易平台 编辑:程序博客网 时间:2024/06/01 17:59

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);        }    }}



0 0
原创粉丝点击