Future的使用

来源:互联网 发布:数据电视怎么调画面 编辑:程序博客网 时间:2024/05/20 06:26
ExecutorService的使用:


     List<Future<List<VO>>> futureList = new ArrayList<Future<List<VO>>>();
//用Executors创建一个ExecutorService
            ExecutorService executorService = Executors.newCachedThreadPool();
            try {
                for (T t : list) 
                   //发起一个线程        
                    Future<List<VO>> f = executorService.submit(new QueryTask(t));
                    futureList.add(f);
                }
                //Future类会等待线程执行完毕,再做操作
                for (Future<List<VO>> future : futureList) {
                    try {
                        rows.addAll(future.get());
                    }catch (Exception e) {
                        throw new RuntimeException("查询任务线程异常");
                    }
                }
            } finally {
            //关闭线程服务
                executorService.shutdown();
            }




   /**
     * 异步查询任务
     */
     private class QueryTask implements Callable<List<VO>> {
        private T t;
        QueryTask(T t) {
            this.t = t;
        }


          /**
               * @see java.util.concurrent.Callable#call()
                   */
                 @Override
                 public List<VO> call() throws Exception {
                    //具体的执行方法
                       return method(this.t);
                 }
              }


ExecutorService的使用场景:可以在页面查询的时候使用,比如查询多个接口,可以起多个线程,最后合并结果,可以节约时间,防止请求超时。虽然可以在代码中设置线程池参数,这样就不利于维护。
原创粉丝点击