组合springMVC使用ExecutorService多线程处理
结合springMVC使用ExecutorService多线程处理
package com.qyedi.module.order.service; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.google.common.collect.Lists; import com.qyedi.base.model.order.OrderAdjustVO; import com.qyedi.base.model.order.OrderVO; import com.qyedi.module.order.domain.OrderDisplay; /** * @description java线程池测试服务实现类 * @author jerome * @date 2016年2月16日 * @company qingyun * @copyright copyright (c) 2015 */ @Service public class ExcutorTestService implements IExcutorTestService { private static final Logger log = LoggerFactory.getLogger(ExcutorTestService.class); private static final int THREADNUM = 2; private ExecutorService threadPool; @PostConstruct public void init(){ this.threadPool = Executors.newFixedThreadPool(THREADNUM); log.info("ExcutorTestService.init finished……"); } @PreDestroy public void destroy(){ threadPool.shutdown(); log.info("ExcutorTestService.destroy finished……"); } @Override public void excute(List<OrderDisplay> orderList) { List<FutureTask<OrderAdjustVO>> futureTaskList = Lists.newArrayList(); for(final OrderVO order : orderList){ FutureTask<OrderAdjustVO> futureTask = new FutureTask<OrderAdjustVO>(new Callable<OrderAdjustVO>() { @Override public OrderAdjustVO call() throws Exception { double num = Math.random(); log.info("这里做数据持久化 begin call order : " + order.getOrderId() + " num :" + num); Thread.sleep(1000); OrderAdjustVO orderAdjustVO = new OrderAdjustVO(); log.info("这里做数据持久化 end call order : " + order.getOrderId() + " num :" + num); return orderAdjustVO; } }); futureTaskList.add(futureTask); threadPool.submit(futureTask); } /* 这里会线程阻塞 for (FutureTask<OrderAdjustVO> futureTask : futureTaskList) { double num = Math.random(); try { log.info("遍历futureTask……begin " + num); futureTask.get(); log.info("遍历futureTask……end " + num); } catch (InterruptedException | ExecutionException e) { log.info("@生成报价记录失败:" + e, e); throw new ServiceException("生成报价记录失败!"); } } */ log.info("service方法调用完成,主线程……"); } }