多线程之Future接口

double

Future 接口是可以精确接收线程执行后返回值的

使用方式

  1. ①实现 Callable 接口的 call方法
public class MyCallable implements Callable<String> { @Override public String call() throws Exception { String value = "test"; System.out.println("开始活动: to work"); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("task done"); return value; } }
  1. ②通过线程使用
public class FutureTaskDemo { public static void main(String[] args) { MyCallable myCallable = new MyCallable(); FutureTask<String> futureTask = new FutureTask<>(myCallable); Thread thread = new Thread(futureTask); thread.start(); // 判断线程是否执行完成 if (!futureTask.isDone()) { System.err.println("task return is not, plase wait!"); } try { /** * 通过 get()方法来的 **/ String result = futureTask.get(); System.out.println("task 返回结果" + result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("结束"); } }
  1. ③通过线程池使用
public class FutureTaskDemo { public static void main(String[] args) { FutureTask<String> futureTask = new FutureTask<>(new MyCallable()); ExecutorService executorService = Executors.newCachedThreadPool(); // 提交 executorService.submit(futureTask); if (!futureTask.isDone()) { System.err.println("还没结束"); } try { String str = futureTask.get(); System.out.println("返回结果:" + str); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }finally { executorService.shutdown(); } } }

思考

  • 如果 Future 接口的实现类设置了延迟3秒返回值,添加到线程调用了 start() 方法后,如果当前线程又设置延迟4秒,那么在4秒后调用 get() 方法是立刻就获取到值么?