1、futuretask类不仅实现了future接口还实现了runnable接口,表示一种可生成结果的runnable。
2、futuretask类实现了future接口的开启和取消任务、查询任务是否完成、获取计算结果方法。
要获取futuretask任务的结果,我们只能通过调用getxxx()系列方法才能获取,当结果还没出来时候这些方法会被阻塞,同时这了任务可以是callable类型(有返回结果),也可以是runnable类型(无返回结果)。
实例
private static void testfuturetask() throws executionexception, interruptedexception { system.out.println(-------------------- testfuturetask --------------------); // 创建一个 futuretask(doonething 任务) futuretask<string> futuretask = new futuretask<>(futuretaskdemo::doonething); // 使用线程池执行 doonething 任务 forkjoinpool.commonpool().execute(futuretask); // 执行 dootherthing 任务 string dootherthingresult = dootherthing(); // 同步等待线程执行 doonething 任务结束 string doonethingresult = futuretask.get(); // 任务执行结果输出 system.out.println(doonethingresult ---->>> + doonethingresult); system.out.println(dootherthingresult ---->>> + dootherthingresult);}
以上就是java异常编程futuretask实例分析的详细内容。
