一、Future 接口中的方法
Future 是专门用于描述异步计算结果的,完美可以通过 Future 对象获取线程计算的结果
boolean cancel(boolean mayInterruptIfRunning)
:试图取消此次任务的执行,取消成功返回true,否则返回falseV get()
:如有必要,等待计算完成,然后获取其结果V get(long timeout, TimeUnit unit)
:如有必要,最多等待指定时间后,获取其结果(如果结果可用);超过指定时间,则抛出异常,不再等待boolean isCancelled()
:如果在任务正常完成前将其取消,则返回trueboolean isDone()
:任务已完成,则返回true
二、使用案例
public class FutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException,TimeoutException {
//创建线程池对象
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Integer> future = executorService.submit(new AddClass(2, 3));
test2(future);
}
/**
* 执行结果:
*/
// 第一次判断任务是否完成:false
// 第一次判断任务是否取消:false
// 计算结果前
// 计算结果后
// 执行结果:5
// 第二次判断任务是否完成:true
// 第二次判断任务是否取消:false
private static void test1(Future<Integer> future) throws ExecutionException, InterruptedException {
System.out.println("第一次判断任务是否完成:" + future.isDone());
System.out.println("第一次判断任务是否取消:" + future.isCancelled());
System.out.println("执行结果:"+future.get().toString());
System.out.println("第二次判断任务是否完成:" + future.isDone());
System.out.println("第二次判断任务是否取消:" + future.isCancelled());
}
/*
*执行结果:
*/
// 计算结果前
// 计算结果后
// 执行结果:5
private static void test2(Future<Integer> future) throws TimeoutException, ExecutionException, InterruptedException {
// System.out.println("取消任务:" + future.cancel(false));
//等待3秒,获取执行结果:5;执行时间必须小于等待时间,否则抛出异常
System.out.println("执行结果:"+future.get(3,TimeUnit.SECONDS).toString());
}
}
class AddClass implements Callable<Integer> {
private int a;
private int b;
public AddClass(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public Integer call() throws Exception {
System.out.println("计算结果前");
Thread.sleep(2000);
System.out.println("计算结果后");
return a + b;
}
}