类型 | 方法 | 说明 |
---|
boolean | cancel(boolean mayInterruptIfRunning) | 试图取消对此任务的执行。 |
V | get() | 如有必要,等待计算完成,然后获取其结果。 |
V | get(long timeout, TimeUnit unit) | 如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。 |
boolean | isCancelled() | 如果在任务正常完成前将其取消,则返回 true。 |
boolean | isDone() | 如果任务已完成,则返回 true。 |
public class FutureDemo {
public static void main(String[] args) throws Exception{
ExecutorService es = Executors.newCachedThreadPool();
Future<Integer> future = es.submit(new MyCall(1, 1));
test03(future);
}
private static void test03(Future<Integer> future) throws Exception{
Integer integer = future.get(1, TimeUnit.SECONDS);
System.out.println("任务执行的结果是:" + integer);
}
private static void test02(Future<Integer> future) {
boolean b = future.cancel(true);
System.out.println("取消任务执行的结果:"+b);
}
private static void test01(Future<Integer> future) throws Exception{
boolean done = future.isDone();
System.out.println("第一次判断任务是否完成:"+done);
boolean cancelled = future.isCancelled();
System.out.println("第一次判断任务是否取消:"+cancelled);
Integer integer = future.get();
System.out.println("任务执行的结果是:"+integer);
boolean done2 = future.isDone();
System.out.println("第一次判断任务是否完成:"+done2);
boolean cancelled2 = future.isCancelled();
System.out.println("第一次判断任务是否取消:"+cancelled2);
}
}
class MyCall implements Callable<Integer>{
private int a;
private int b;
public MyCall(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public Integer call() throws Exception {
String name = Thread.currentThread().getName();
System.out.println(name+"准备开始计算...");
Thread.sleep(2000);
System.out.println(name+"计算完成...");
return a+b;
}
}