概念

FutureTask 能够接收 Callable 类型的参数,用来处理有返回结果的情况

实例

  1. public class FutureTaskDemo {
  2. public static void main(String[] args) throws ExecutionException, InterruptedException {
  3. // 创建任务对象
  4. FutureTask<Integer> task3 = new FutureTask<>(() -> {
  5. System.out.println("hello");
  6. return 100;
  7. });
  8. // 参数1 是任务对象; 参数2 是线程名字,推荐
  9. new Thread(task3, "t3").start();
  10. // 主线程阻塞,同步等待 task 执行完毕的结果
  11. Integer result = task3.get();
  12. System.out.println("结果是:"+result);
  13. }
  14. }