FutureTask 常用的 Api
get():获取任务的返回结果,如果任务没执行完,会一直阻塞等待任务执行完毕。
isDone :结束,正常还是异常结束,或者自己取消,返回true;
isCancelled:任务完成前被取消,返回true;
cancel(boolean):
- 任务还没开始,返回false
- 任务已经启动,cancel(true),中断正在运行的任务,中断成功,返回true,cancel(false),不会去中断已经运行的任务。
- 任务已经结束,返回false。
代码实例:
package com.jym.concurrent;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class UseCallable {
public static class CallThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
Thread.sleep(10);
for (int index = 99999; index >= 90000; index--) {
sum = sum + index;
}
return sum;
}
}
public static void main(String[] args) throws Exception {
CallThread callThread = new CallThread();
FutureTask<Integer> integerFutureTask = new FutureTask<>(callThread);
Thread thread = new Thread(integerFutureTask);
thread.start();
Random random = new Random();
boolean b = random.nextBoolean();
if (b) {
System.out.println("计算的结果为: " + integerFutureTask.get());
} else {
boolean cancel = integerFutureTask.cancel(true);
System.out.println("暂停任务: " + cancel);
}
}
}