MyThread3.java 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. package com.sf.javase.thread;
  2. import java.util.concurrent.Callable;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.FutureTask;
  5. public class MyThread3 implements Callable<String> {
  6. // 此时是call方法
  7. @Override
  8. public String call() throws Exception {
  9. Thread.sleep(2000);
  10. return "hello callable";
  11. }
  12. public static void main(String[] args) throws ExecutionException, InterruptedException {
  13. // Callable Future
  14. Callable<String> callable = new MyThread3();
  15. // 用来接收callable执行的结果
  16. FutureTask<String> futureTask = new FutureTask<>(callable);
  17. // 相当于把FutureTask作为Runnable传给Thread
  18. // 所以Thread执行run()方法时 执行的是FutureTask的run()方法
  19. // 而FutureTask的run()方法 又调用了Callable的call()方法
  20. // 所以最终效果是 call()才是真正的线程执行逻辑
  21. Thread thread = new Thread(futureTask);
  22. thread.start();
  23. // 通过get 接收结果 是一种阻塞的等待
  24. String result = futureTask.get();
  25. System.out.println(result);
  26. }
  27. }