Future获取子线程的执行结果
目录
1. Future 和 Callable
1. 1 Runnable的缺陷
1.2 Callable 接口
1.3 Future 和 Callable 关系
1.4 Future 的5个主要方法
1.4.1 get()方法:获取结果
1.4.2 get(long timeout,TimeUnit unit) 方法: 超时不获取
1.4.3 cancel 方法:取消任务的执行
1.4.4. isDone方法: 判断线程是否执行完毕
1.4.5. isCanaelled 方法: 判断是否被取消
2 Futrue代码演示
2.1 线程池的submit方法返回Future对象,get基本用法
2.2 Callable 的Lambda 表达式形式
2.3 多个任务,用Future数组来获取结果
2.4 抛出异常的情况和isDone
2.5 默认超时时间和取消
2.5 cancel 方法:取消任务的执行
3. FutureTask 获取结果
1. Future 和 Callable
1. 1 Runnable的缺陷
- 不能返回一个返回值
- 无法抛出一个 checked exception
1.2 Callable 接口
- 类似于Runnable,被其他线程执行的任务
- 实现call方法,有返回值
public interface Callable {/*** Computes a result, or throws an exception if unable to do so.** @return computed result* @throws Exception if unable to compute a result*/V call() throws Exception;
}
1.3 Future 和 Callable 关系
- 我们可以用 Future.get 获取 Callable接口返回的执行结果,还可以通过Futrue.isDone 来判断任务是否已经执行完了,以及取消这个任务,限时获取任务的结果等
- 在call()未执行完毕之前,调用get()的线程(假定此时是主线程),直到call()方法返回了结果后,此时future.get()才会得到该结果,然后主线程才会切换到runnable状态
- 所以Future是一个存储器,它存储了call()这个任务的结果,然而这个任务的执行时间是无法提前确定的,因为这完全取决于call()方法执行的情况
1.4 Future 的5个主要方法
1.4.1 get()方法:获取结果
- get 方法的行为取决于Callable任务的状态,只有以下这 5 种情况:
- 任务正常完成:get 方法会立刻返回结果
- 任务尚未完成(任务还没开始或进行中):get将阻塞并指导任务完成
- 任务执行过程中抛出Exception:get方法会排出ExecutionExecption:这里的抛出异常,是call()执行时产生的那个异常,看到这个异常类型是java.until.concurrent.ExecutionException.不论call()执行时抛出的异常类型是什么,最后get方法抛出的异常类型都是ExecutionException,任务被取消:get方法会抛出 CallcellationException
- 任务超时:get方法有一个重载方法,是传入一个延迟时间的,如果时间到了还没有获取结果,get方法就会排出TimeoutExceptionget
1.4.2 get(long timeout,TimeUnit unit) 方法: 超时不获取
- 用get(long timeout,TimeUnit unit) 方法时,如果call()在规定时间内完成了任务,那么就会正常获取到返回值,如果再制定时间内没有计算出结果,那么就会抛出TimeoutException
- 超时不获取,任务需取消
1.4.3 cancel 方法:取消任务的执行
1.4.4. isDone方法: 判断线程是否执行完毕
1.4.5. isCanaelled 方法: 判断是否被取消
2 Futrue代码演示
2.1 线程池的submit方法返回Future对象,get基本用法
首先,我们要给线程池提交我们的任务,提交时线程池会立刻返回给我们一个空的Future容器,当线程的任务一旦执行完毕,也就是当我们可以获取结果的时候,线程池便会把该结果填入到之前给我们的那个Future中去(而不是创建一个新的Future),我们此时便可以从该Future中获得任务执行的结果
/*** 描述:演示一个Future的使用方法*/
public class OneFuture {public static void main(String[] args) {ExecutorService service = Executors.newFixedThreadPool(10);Future future = service.submit(new CallableTask());try {System.out.println(future.get());}catch (ExecutionException e){e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} finally {service.shutdown();}}static class CallableTask implements Callable {@Overridepublic Integer call() throws Exception {Thread.sleep(3000);return new Random().nextInt();}}
}
2.2 Callable 的Lambda 表达式形式
public class OneFutureLambda {public static void main(String[] args) {ExecutorService service = Executors.newFixedThreadPool(10);Callable callable = ()->{Thread.sleep(3000);return new Random().nextInt();};Future future = service.submit(callable);try {System.out.println(future.get());}catch (ExecutionException e){e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();} finally {service.shutdown();}}
2.3 多个任务,用Future数组来获取结果
/*** 描述: 演示批量提交任务时,用List来批量接收结果*/
public class MultiFutures {public static void main(String[] args) {ExecutorService service = Executors.newFixedThreadPool(2);ArrayList futures = new ArrayList<>();for (int i = 0; i < 20; i++) {Future future = service.submit(new CallableTask());futures.add(future);}for (int i = 0; i < 20; i++) {Future future = futures.get(i);try {Integer integer = future.get();System.out.println(integer);}catch (Exception e){e.printStackTrace();}}}static class CallableTask implements Callable {@Overridepublic Integer call() throws Exception {Thread.sleep(3000);return new Random().nextInt();}}
}
2.4 抛出异常的情况和isDone
/*** 描述: 演示 get 方法过程中抛出异常,for循环为了演示抛出异常的时机,并不是说一产生异常就抛出,* 直到我们get执行时,才会抛出*/
public class GetException {public static void main(String[] args) {ExecutorService service = Executors.newFixedThreadPool(20);Future future = service.submit(new CallableTask());try {for (int i = 0; i < 5; i++) {System.out.println(i);Thread.sleep(500);}System.out.println(future.isDone());future.get();} catch (InterruptedException e) {e.printStackTrace();System.out.println("InterruptedException 异常");} catch (ExecutionException e) {e.printStackTrace();System.out.println("ExecutionException 异常");}}static class CallableTask implements Callable {@Overridepublic Integer call() throws Exception {throw new IllegalArgumentException("Callable 抛出异常");}}
}
2.5 默认超时时间和取消
/*** 描述: 演示get的超时方法,需要注意超时后处理,调用future.cancel(),* 演示cancel传入true和false的区别,代表是否中断正在执行的任务*/
public class TimeOut {private static final Ad DEFAULT_AD = new Ad("无网络时候的默认广告");private static final ExecutorService exec = Executors.newFixedThreadPool(10);static class Ad{String name;public Ad(String name) {this.name = name;}@Overridepublic String toString() {return "Ad{" +"name='" + name + '\'' +'}';}}static class FetchAdTask implements Callable{@Overridepublic 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 future = exec.submit(new FetchAdTask());Ad ad;try {ad = future.get(4000,TimeUnit.SECONDS);} catch (InterruptedException e) {ad = new Ad("被中断时候的默认广告");} catch (ExecutionException e) {ad = new Ad("异常时候的默认广告");} catch (TimeoutException e) {ad = new Ad("超时时候的默认广告");System.out.println("超时,为获取到广告");boolean cancel = future.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();}
}
2.5 cancel 方法:取消任务的执行
- 如果这个任务还没有开始执行,那么这种情况最简单,任务会被正常的取消,未来也不会被执行,方法返回true
- 如果任务已完成,或者已取消,那么cancel()方法会执行失败,方法返回false
- 如果这个任务已经开始执行了,那么取消这个方法将不会直接取消该任务,而是会根据我们填的参数mayInterruptIfRunning做判断
3. FutureTask 获取结果
把Callable实例当作参数,生成FutureTask的对象,然后把这个对象当作一个Runnable对象,用线程池或另起线程去执行这个Runnable对象,最后通过FutureTask 获取刚才执行的结果
/*** 描述: 演示FutureTask用法*/
public class FutureTaskDemo {public static void main(String[] args) {Task task = new Task();FutureTask futureTask = new FutureTask<>(task);new Thread(futureTask).start();try {System.out.println(futureTask.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}
}class Task implements Callable{@Overridepublic Integer call() throws Exception {System.out.println("子线程正在计算");Thread.sleep(3000);int sum = 0;for (int i = 0; i <= 100; i++) {sum+=i;}return sum;}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
