Runnable接口
1.Runnable的缺陷
① 不能返回一个返回值
② 不能抛出checked Exception
2.Runnable为什么设计成这样
① 如果run方法能够抛出异常,此时由Thread类来接收,在run方法声明了异常,处理类也不是自己编写的,能够处理的就是在run方法中自己try…catch
② 针对于无法抛出检查异常这个缺陷的补救措施
Callable接口
类似于Runnable,被其他线程执行的任务
实现call方法
有返回值
Future类
1.Future的作用
一个方法的计算可能很耗时,这个时候你在计算的过程中我没有必要一直在原地等你,浪费自己的时间,如果遇到一个耗时的方法就很浪费时间,这时让子线程去执行,子线程去执行的时候我可以做其他事情,直到我想要获取你结果的时候再用Future去控制,包括你的任务是否取消、正常运行的结果返回,这一系列结果都可以控制
2.Callable和Future的关系
① 我们可以用Future.get来获取Callable接口返回的执行结果,还可以通过Future.isDone()来判断任务是否已经执行完了,以及取消这个任务,限时获取任务的结果等
② 在call()未执行完毕之前,调用get()的线程(假定此时是主线程)会被阻塞,直到call方法返回了结果后,此时future.get()才会得到该结果,然后主线程才会切换到Runnable状态
③ 所以Future是一个存储器,它存储了call()这个任务的结果,而这个任务的执行时间是无法提前确定的,因为这完全取决于call()方法执行的情况
3.Future的方法
① get()方法:获取结果,get方法的行为取决于Callable任务的状态,只有以下这5种情况
-
任务正常完成:get方法会立刻返回结果
-
任务还未完成(任务还没开始或进行中),get将阻塞并直到任务完成
-
任务执行过程中抛出Exception,get方法会抛出ExceptionException:这里抛出的异常,是call()执行时产生的哪个异常,看到这个异常类型是java.util.concurrent.ExceptionException。不论call()执行时抛出的异常类型是什么,最后get方法抛出的异常类型都是ExceptionException
-
任务被取消:get方法会抛出CancellationException
-
任务超时:get方法有一个重载方法,是传入一个延迟时间的,如果时间到了还没有获得结果,get方法就会抛出TimeoutException
② get(long Time,TimeUnit unit):有超时的获取
-
超时的需求很常见
-
用get(long Time,TimeUnit unit)方法时,如果call()在规定的时间内完成了任务,那么就会正常获取到返回值,而如果在指定的时间内没有计算出结果,那么就会抛出TimeoutException
-
超时不获取,任务需取消
③ cancel(boolean mayInterruptIfRunning):尝试取消执行此任务。
-
如果这个任务还没有开始执行,那么这种情况最简单,任务会被正常的取消,未来也不会被执行,方法返回true
-
如果任务已经完成,或者已取消,那么cancel()方法会执行失败,方法返回false
-
如果这个任务已经开始执行了,那么这个取消方法将不会直接取消该任务,而是会根据我们填的参数mayInterruptIfRunning做判断
注:
Future.cancel(true)适用于:
- 任务能够处理interrupt
Future.cancel(false)仅用于避免启动尚未启动的任务,适用于:
-
未能处理interrupt的任务
-
不清楚任务是否支持取消
-
需要等待已经开始的任务执行完成
④ isDone()方法:判断线程是否执行完毕
⑤ isCanceled()方法:判断是否被取消
4.Future的用法
① 用法1:线程池的submit方法返回Future对象
首先,我们要给线程池提交我们的任务,提交时线程池会立刻返回给我们一个空的Future容器,当线程的任务一旦执行完毕,也就是当我们
可以获取结果的时候,线程池便会把该结果填入到之前给我们的那个Future中去(而不是创建一个新的Future),我们此时便可以从该Future中获得任务执行的结果
- get基本用法
/**
* 演示一个Future的使用方法
*/
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();
}
}
}
- Callable的Lambda表达式形式
/**
* 演示一个Future的使用方法,Lambda表达式形式
*/
public class OneFutureLambda {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
Callable<Integer> callable =()->{
Thread.sleep(3000);
return new Random().nextInt();
};
Future<Integer> future = service.submit(callable);
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
service.shutdown();
}
}
- 多个任务,用Future来获取结果
/**
* 演示批量提交任务时,用List来批量接收结果
*/
public class MultiFutures {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(20);
ArrayList<Future> 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();
}
}
}
static class CallableTask implements Callable<Integer>{
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt();
}
}
}
- 任务执行过程中抛出Exception和isDone演示
public class TimeOut {
private static final Ad DEFAULT_AD = new Ad("无网络时候的默认广告");
private static final ExecutorService exec = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
TimeOut timeOut = new TimeOut();
timeOut.printAd();
}
static class Ad {
String name;
public Ad(String name) {
this.name = name;
}
@Override
public String toString() {
return "Ad{" +
"name='" + name + '\'' +
'}';
}
}
static class FetchTask 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("旅游订票那家强?找某程");
}
}
private void printAd() {
Future<Ad> f = exec.submit(new FetchTask());
Ad ad;
try {
ad = f.get(2000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
ad = new Ad("被中断时候的默认广告");
} catch (ExecutionException e) {
ad = new Ad("异常时候的默认广告");
} catch (TimeoutException e) {
ad = new Ad("超时时候的默认广告");
System.out.println("超时,未获取到广告");
boolean cancel = f.cancel(true);
System.out.println("cancel的结果" + cancel);
}
exec.shutdown();
System.out.println(ad);
}
}
② 用法2:用FutureTask来创建Future
-
用FutureTask来获取Future和任务的结果
-
FutureTask是一种包装器,可以把把Callable转换成Future和Runnable,它同时实现二者的接口
-
所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值
-
把Callable实例当作参数,生成FutureTask的对象,然后把这个对象当作一个Runnable对象,用线程池或或另启线程去执行这个Runnable对象,最后通过FutureTask获取刚才执行的结果
public class FutureTaskDemo {
public static void main(String[] args) {
Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask(task);
//new Thread(futureTask).start();
ExecutorService service = Executors.newCachedThreadPool();
service.submit(futureTask);
try {
System.out.println("task运行结果" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
static class Task implements Callable<Integer> {
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
System.out.println("子线程正在运算");
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
}
}
}
Future的注意点
① 当for循环批量获取Future的结果时,容易发生一部分线程很慢的情况,get方法调用时应使用timeout限制
② Future的生命周期不能后退,生命周期只能前进,不能后退。就和线程池的生命周期一样,一旦完全完成了任务,它就永久停在了"已完成"的状态,不能重头再来