先写个Future调用isDone()方法,返回结果是正常的示例
public class SpringbootApplication {
//构建一个线程任务
static class DoSomeThing implements Callable {
@Override
public Object call() throws Exception {
return "正常返回";
}
}
public static void main(String[] args) throws Exception {
FutureTask future = new FutureTask(new DoSomeThing());
new Thread(future).start();
//等待5秒
TimeUnit.SECONDS.sleep(5);
System.out.println(future.isDone());
System.out.println(future.get());
}
}
运行结果如下:
再写个Future调用isDone()方法,返回结果是异常的示例
public class SpringbootApplication {
//构建一个线程任务
static class DoSomeThing implements Callable {
@Override
public Object call() throws Exception {
throw new RuntimeException("异常!!!");
}
}
public static void main(String[] args) throws Exception {
FutureTask future = new FutureTask(new DoSomeThing());
new Thread(future).start();
//等待5秒
TimeUnit.SECONDS.sleep(5);
System.out.println(future.isDone());
System.out.println(future.get());
}
}
运行结果如下:
可以发现即使是出现了异常,isDone()方法结果一样是true。
总结
首先,不管是异常还是正常,只要运行完毕了,isDone()方法结果一样是true,其次即使自定义的是RuntimeException,get拿到的异常还是ExecutionException,最后还可以发现,即使任务一开始运行时就出现了异常,也是等到调用了get方法后才会抛出。