FutureTask获取线程返回值

  • 定义线程池:

    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> taskList = Lists.newArrayList();
    
       // 异步执行
       for (int i = 0; i < 10; i++) {
           FutureTask ft = new FutureTask(new TestThread(i));
           taskList.add(ft);
           executor.submit(ft);
       }
    
       // TODO do something
    
       FutureTask ft;
       // 获取异步执行结果
       for (int i = 0; i < taskList.size(); i++) {
           ft = taskList.get(i);
           System.out.println("线程" + i + " 返回数据:" + ft.get());
       }
    }

你可能感兴趣的:(JAVA)