spring多线程返回值 并对多个返回值进行操作

来源:互联网 发布:网络剪刀手中文版下载 编辑:程序博客网 时间:2024/06/06 05:38

最近遇到一个问题:有一大堆的债券,需要根据不同类别的标签进行筛选出需要的债券,并且还要根据条件对这些标签分别进行并和或操作。

最终决定使用callable+future来实现:

具体代码如下:

@RequestMapping("/test")public Object test(HttpServletRequest request){try{//创建一个线程池ExecutorService pool = Executors.newFixedThreadPool(2);//创建多个有返回值的任务List<Future<List<String>>> list = new ArrayList<>();Callable<List<String>> c1 = myCallable01();//执行任务并获取Future对象Future<List<String>> f1 = pool.submit(c1);list.add(f1);Callable<List<String>> c2 = myCallable02();//执行任务并获取Future对象Future<List<String>> f2 = pool.submit(c2);list.add(f2);//关闭线程池pool.shutdown();List<String> list1 = list.get(0).get();List<String> list2 = list.get(1).get();//取并集list2.removeAll(list1);list1.addAll(list2);}catch{}return "";}public Callable<List<String>> myCallable01(){return new Callable<List<String>>(){@Overridepublic List<String> call() throws Exception{Thread.sleep(6000);List<String> list = new ArrayList<>();list.add("aaa");list.add("bbb");list.add("ccc");return list;}}}public Callable<List<String>> myCallable02(){return new Callable<List<String>>(){@Overridepublic List<String> call() throws Exception{Thread.sleep(9000);List<String> list = new ArrayList<>();list.add("ccc");list.add("ddd");list.add("eee");return list;}}}

阅读全文
1 0