11.1 Future与Callable的关系
11.1.1 Runnable的缺陷
- 为什么有这样的缺陷 ?
- Runnable为什么设计成这样?
- 针对于无法抛出检查后异常这 个缺陷的补救措施
缺陷就是不能返回值,不能抛出受检异常,不能返回值是因为Runnable接口设计如此,不能抛出受检异常,是因为即使抛出也会交个Thread或者线程池处理,不如直接在run方法内部处理。
11.1.2 Callable接口
- 类似于Runnable ,被其它线程执行的任务实现call方法
- 有返回值
- 优点:第一返回泛型,第二可以抛出受检异常。
11.1.3 Future类
Future的作用是用来接收Callable任务执行结果的。
11.1.3 Callable和Future的关系
- 我们可以用Future.get来获取Callable接口返回的执行结果,还可以通过Future.isDone()来判断任务是否已经执行完了,以及取消这个任务,限时获取任务的结果等
- 在call()未执行完毕之前,调用get()的线程(假定此时是主线程)会被阻塞,直到call()方法返回了结果后,此时future.get()才会得到该结果,然后主线程才会切换到runnable状态
- 所以Future是一个存储器,它存储了call()这个任务的结果,而这个任务的执行时间是无法提前确定的,因为这完全取决于cal()方法执行的情况
11.2 Future的主要方法
Future的主要方法:一共五个
Future的主要方法
- cancel方法:取消执行任务
- isDone()方法:判断线程是否执行完毕
- isCancelled()方法 :判断是否被取消
- get()方法:获取结果
- get(long timeout, TimeUnit unit) :有超时的获取
11.2.1 get()方法:获取结果
get方法的行为取决于Callable任务的状态,只有以下这5种情况:
1.任务正常完成: get方法会立刻返回结果
2.任务尚未完成(任务还没开始或进行中) : get将阻塞并直到任务完成。
3.任务执行过程中抛出Exception : get方法会抛出ExecutionException :这里的抛出异常,是call()执行时产生的那个异常,看到这个异常类型是java.util.concurrent.ExecutionException。不论call()执行时抛出的异常类型是什么,最后get方法抛出的异常类型都是ExecutionException。
4.任务被取消: get方法会抛出CancellationException
5.任务超时: get方法有一个重载方法,是传入-个延迟时间的,如果时间到了还没有获得结果, get方法就会抛出TimeoutException。
11.2.2 get(long timeout, TimeUnit unit) :有超时的获取
- 超时的需求很常见
- 用get(long timeout, TimeUnit unit)方法时,如果cal()在规定时间内完成了任务,那么就会正常获取到返回值;而如果再指定时间内没有计算出结果,那么就会抛出TimeoutException
- 超时不获取,任务需取消
11.2.3 cancel方法
cancel方法:取消任务的执行
1.如果这个任务还没有开始执行,那么这种情况最简单,任务会被正常的取消,未来也不会被执行,方法返回true。
2.如果任务已完成,或者已取消:那么cancel(方法会执行失败,方法返回false。
3.如果这个任务已经开始执行了, 那么这个取消方法将不会直接取消该任务,而是会根据我们填的参数mayInterruptIfRunning做判断:
Future.cancel(true)适用于:
1.任务能够处理interruptFuture.cancel(false)仅用于避免启动尚未启动的任务, 适用于:
2.未能处理interrupt的任务
3.不清楚任务是否支持取消
4.需要等待已经开始的任务执行完成
11.3 批量接收结果
用法一:线程池的submit方法返回Future对象
- 首先,我们要给线程池提交我们的任务,提交时线程池会立刻返回给我们一个空的Future容器。当线程的任务一旦执行完毕也就是当我们可以获取结果的时候,线程池便会把该结果填入到之前给我们的那个Future中去(而不是创建一个新的Future ) , 我们此时便可以从该Future中获得任务执行的结果
下面为get的基本用法
public class OneFuture {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
Future<Integer> future = service.submit(new CallableTask());
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
service.shutdown();
}
static class CallableTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt();
}
}
}
也可以通过,lambada表达的形式表示。
public class OneFutureLambada {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
Future<Integer> future = service.submit(() -> {
Thread.sleep(3000);
return new Random().nextInt();
});
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
service.shutdown();
}
}
多个任务,用Future数组来获取结果。
public class MultiFutures {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(20);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Future<Integer> future = service.submit(new CallableTask());
futures.add(future);
}
Thread.sleep(5000);
for (int i = 0; i < 20; i++) {
Future<Integer> future = futures.get(i);
try {
Integer integer = future.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
service.shutdown();
}
static class CallableTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt();
}
}
}
11.4 执行时异常和isDone演示
演示get方法中抛出异常,for循环为了演示抛出Exception时机,并不是说一产生异常就抛出,直到我们get执行时才会抛出。
�
public class GetException {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(20);
Future<Integer> future = service.submit(new CallableTask());
try {
for (int i = 0; i < 5; i++) {
System.out.println(i);
Thread.sleep(1000);
}
//只会打印是否完成,无论执行结果成功还是失败
System.out.println(future.isDone());
// 只有执行get的时候才会感知到异常抛出
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("InterruptedException异常");
} catch (ExecutionException e) {
e.printStackTrace();
System.out.println("ExecutionException异常");
}
service.shutdown();
}
static class CallableTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
throw new IllegalArgumentException("callable抛出异常");
}
}
11.5 cancel方法与中断线程
使用cancel方法对任务进行取消,下面的场景是假设,要去请求广告信息如果请求超时,则使用默认的广告去展示这样一个场景。
下面的例子里是用get的超时方法,如果超过2秒没有获取到,则就会抛出,超时异常,
下面对超时异常进行了捕获,并且在这个catch中,对任务进行了取消,这里有两种情况,cancel传入的true和false, 传入true把线程中断,收到中断信号,抛出InterruptedException,并且中断之后,也不会收到catch中传出来的返回结果, false程序会继续运行,会正常运行到结束,不会发出中断信号。
/**
* 演示get的超时方法,需要注意超时后处理,调用cancel方法,演示cancel传入true和false的区别
* 代表是否中断正在执行的任务
*
*/
public class TimeOut {
private static final Ad DEFAULT_AD = new Ad("无网络时候的默认广告");
public static final ExecutorService exec = Executors.newFixedThreadPool(10);
static class Ad {
String name;
public Ad(String name) {
this.name = name;
}
@Override
public String toString() {
return "Ad{" +
"name='" + name + '\'' +
'}';
}
}
static class FetchAdTask implements Callable<Ad> {
@Override
public Ad call() throws Exception {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("sleep 期间被中断了");
return new Ad("被中断的默认广告");
}
return new Ad("旅游订票哪家强?找某程");
}
}
public void printAd() {
Future<Ad> f = exec.submit(new FetchAdTask());
Ad ad;
try {
ad = f.get(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
ad = new Ad("被中断的默认广告");
e.printStackTrace();
} catch (ExecutionException e) {
ad = new Ad("异常时的默认广告");
e.printStackTrace();
} catch (TimeoutException e) {
ad = new Ad("超时默认广告");
System.out.println("超时未获取广告");
// 传入true把线程中断,收到中断信号,抛出InterruptedException
// false程序会继续运行,会正常运行到结束,不会发出中断信号
boolean cancel = f.cancel(false);
System.out.println("cancel的结果" + cancel);
}
exec.shutdown();
System.out.println(ad);
}
public static void main(String[] args) {
TimeOut timeOut = new TimeOut();
timeOut.printAd();
}
}
传入false的意义,如果中断别人,没有做中断检查,如果开始了,都能让任务顺利执行。
这里true和false参数的意义就是有些任务不具备处理中断的能力,或者要保证即使中断,也要执行完整个流程。
11.6 用法二:用FutureTask获取结果
11.6.1 基本用法
- 用FutureTask来获取Future和任务的结果
- FutureTask是一 种包装器,可以把Callable转化成Future和Runnable,它同时实现二者的接口
- 把Callable实例当作参数,生成Future Task的对象,然后把这个对象当作-个Runnable对象,用线程池或另起线程去执行这个Runnable对象,最后通过Future Task获取刚才执行的结果
代码演示 ```java public class FutureTaskDemo {
public static void main(String[] args) {
Task task = new Task(); FutureTask<Integer> integerFutureTask = new FutureTask<>(task);
// new Thread(integerFutureTask).start();
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.submit(integerFutureTask);
try {
Integer integer = integerFutureTask.get();
System.out.println("task 运行结果:" + integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class Task implements Callable
@Override
public Integer call() throws Exception {
System.out.println("子线程正在计算");
Thread.sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
}
11.7 Future注意点
- 当for循环批量获取future的结果时,容易发生一部分线程很慢的情况, get方法调用时应使用timeout限制或者使用CompleteableFuture
- Future的生命周期不能后退。就和线程池的生命周期一样,一旦完全完成了任务,它就永久停在了“已完成”的状态,不能重头再来