java线程池带返回值例子(callable future)
package com.zaki.threads; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class ThreadPoolWithReturn { static ExecutorService executorService = Executors.newFixedThreadPool(2); public static void main(String[] args) { PoolThread1 thread1 = new PoolThread1(); PoolThread2 thread2 = new PoolThread2(); //将Future包装进List,实现添加结果 List<Future> resultList = new ArrayList<Future>(); for (int i = 0; i < 3; i++) { System.out.println("线程池已提交第:" + i + " 次"); Future res1 = executorService.submit(thread1); Future res2 = executorService.submit(thread2); //将获取的结果添加进List resultList.add(res1); resultList.add(res2); } System.out.println("正在关闭线程池..."); executorService.shutdown(); System.out.println("线程池已关闭."); System.out.println("开始输出线程返回结果..."); //线程池运行结束,打印结果 for (int i = 0; i < resultList.size(); i++) { Future future = resultList.get(i); try { System.out.println(future.get()); } catch (InterruptedException | ExecutionException e) { } } } } /** * 线程1 */ class PoolThread1 implements Callable { @Override public Object call() throws Exception { try { Thread.sleep(500); } catch (Exception e) {} return "本条数据来自线程1的返回值"; } } /** * 线程2 */ class PoolThread2 implements Callable { @Override public Object call() throws Exception { try { Thread.sleep(500); } catch (Exception e) {} return "本条数据来自线程2的返回值"; } }