java多线程并行操作

    public Map<String, Object> myTrainListDatasTotalCount(HttpServletRequest request) {
        Map<String, Object> attributes = new HashMap<String, Object>();
        BaseInfoEntity baseInfo = this.getBaseInfo(request);

        //通过多个线程并查询
        ExecutorService service = Executors.newFixedThreadPool(3); //创建线程池
        BlockingQueue<Future<String[]>> queue = new LinkedBlockingQueue<Future<String[]>>(); //创建队列
        
        Future<String[]> future = service.submit(this.getWholeMyTrainListCount(baseInfo,null,"all"));
        queue.add(future);
        
        Future<String[]> future1 = service.submit(this.getWholeMyTrainListCount(baseInfo,null,"wait"));
        queue.add(future1);
        
        Future<String[]> future2 = service.submit(this.getWholeMyTrainListCount(baseInfo,null,"complete"));
        queue.add(future2);
        
        int queueSize = queue.size();
        for (int i = 0; i < queueSize; i++) {
            try {
                String[] str = queue.take().get();
                
                //结果处理过程
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        service.shutdown();
        
        return attributes;
    }
    
    public Callable<String[]> getWholeMyTrainListCount(final BaseInfoEntity baseInfo,final WeixPageBean weixPageBean,final String type) { //传递的参数都需要使用final修饰 
         Callable<String[]> callable = new Callable<String[]>() {
                public String[] call() throws Exception {
                    String[] str = new String[2];
                        
                        //处理过程
                        
                    return str;
                }
            };
            return callable;
    }

 

posted @ 2020-07-09 19:21  天线宝宝出来玩  阅读(563)  评论(0编辑  收藏  举报