FutureTask主要用来包装Callable实现,启动线程不能直接使用Callable.start,具体使用如下:
/**
*类说明:演示Future等的使用
*/
public class UseFuture {
/*实现Callable接口,允许有返回值*/
private static class UseCallable implements Callable<Integer>{
private int sum;
@Override
public Integer call() throws Exception {
System.out.println("Callable子线程开始计算");
Thread.sleep(2000);
for(int i=0;i<5000;i++) {
sum = sum+i;
}
System.out.println("Callable子线程计算完成,结果="+sum);
return sum;
}
}
public static void main(String[] args)
throws InterruptedException, ExecutionException {
UseCallable useCallable = new UseCallable();
FutureTask<Integer> futureTask = new FutureTask<>(useCallable);
new Thread(futureTask).start();
Random r = new Random();
SleepTools.second(1);
if(r.nextBoolean()) {//随机决定是获得结果还是终止任务
System.out.println("Get UseCallable result = "+futureTask.get());
}else {
System.out.println("中断计算");
System.out.println(futureTask.cancel(true));
}
}
}
工具类:SleepTools请参考https://blog.csdn.net/qq_42709262/article/details/88971211
或自己实现也可
需要注意的是,当我们调用get()方法的时候,线程是阻塞的,也就是说,如果我们这个useCallable任务没有完成,那么主线程不会继续执行下去,直到我们的useCallable任务完成并且获得结果才会继续执行
cancel(boolean):
- 任务还没开始,返回false
- 任务已经启动,cancel(true),中断正在运行的任务,中断成功,返回true,cancel(false),不会去中断已经运行的任务
- 任务已经结束,返回false
如图:
使用场景:包含图片和文字的文档的处理:图片(云上),可以用future去取图片,主线程继续解析文字。