FutureTask获取线程返回值

来源:互联网 发布:农村淘宝服务站佣金 编辑:程序博客网 时间:2024/05/29 17:47
  • 定义线程池:

    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1,    new ThreadFactory() {        @Override        public Thread newThread(Runnable r) {            Thread thread = new Thread(r);            thread.setName("TEST-THREAD");            return new Thread(r);        }    });
  • 定义线程:

    private class TestThread implements Callable<Boolean> {   private int id;   public TestThread(int id) {       this.id = id;   }   @Override   public Boolean call() throws Exception {       System.out.println("执行线程id:" + id);       try {           // TODO do something       } catch (Exception e) {           return Boolean.FALSE;       }       return Boolean.TRUE;   }}
  • test方法:

    public static void main(String[] args) throws Exception {   List<FutureTask<Boolean>> taskList = Lists.newArrayList();   // 异步执行   for (int i = 0; i < 10; i++) {       FutureTask<Boolean> ft = new FutureTask(new TestThread(i));       taskList.add(ft);       executor.submit(ft);   }   // TODO do something   FutureTask<Boolean> ft;   // 获取异步执行结果   for (int i = 0; i < taskList.size(); i++) {       ft = taskList.get(i);       System.out.println("线程" + i + " 返回数据:" + ft.get());   }}
0 0