多线程

来源:互联网 发布:js 简单加密算法 编辑:程序博客网 时间:2024/06/05 00:29
private void execute(List<String> activityIdList, ElActivityMessageVo elActivityMessageVo, List<SetMealGood> setMealGoods,
                          SetMealSyncService setMealSyncService) {
        ExecutorService executor = null;
        CountDownLatch countDown = null;
        try {
            int size = null != activityIdList ? activityIdList.size() : 0;
            if (size > 0) {
                executor = Executors.newFixedThreadPool(20);
                countDown = new CountDownLatch(size);


                for (int i = 0; i < size; i++) {
                    executor.submit(new TaskHandler(countDown, new Task(activityIdList.get(i), elActivityMessageVo, setMealGoods,
                             setMealSyncService)));
                }
                countDown.await();
            }
            logger.info("同步套餐活动完成,活动id:"+ ",同步数量:" + size);


        } catch (Exception e) {
            logger.error("执行套餐活动同步出现异常", e);
        } finally {
            if (null != executor) {
                executor.shutdown();
            }
        }
    }


    public class TaskHandler implements Runnable {
        private Task task;
        private CountDownLatch countDownLatch;


        public TaskHandler(CountDownLatch countDownLatch, Task task) {
            this.task = task;
            this.countDownLatch = countDownLatch;
        }


        public void run() {
            try {
                task.start();
            } finally {
                countDownLatch.countDown();
            }
        }
    }


    class Task {
        private ElActivityMessageVo elActivityMessageVo;
        private String activityId;
        private List<SetMealGood> setMealGoods;
        private SetMealSyncService setMealSyncService;




        private Task(String activityId, ElActivityMessageVo elActivityMessageVo, List<SetMealGood> setMealGoods,
                     SetMealSyncService setMealSyncService) {
            this.activityId = activityId;
            this.elActivityMessageVo = elActivityMessageVo;
            this.setMealGoods = setMealGoods;
            this.setMealSyncService = setMealSyncService;
        }


        public void start() {
            //使用一个服务类,方便提交事务。
            this.setMealSyncService.syncSetMeal(activityId, elActivityMessageVo, setMealGoods);
        }
    }
0 0
原创粉丝点击