Future和Callable
Callable类似于Runnable,别其他线程执行的任务;最大的区别是实现call方法,有返回值
Future 和 Callable 关系:
- 我们可以使用Future.get方法获取callable接口返回的执行结果,还可以通过Futrue.isDone 来判断任务是否已经执行完了,以及取消这个任务,限时获取任务的结果等
- 在call()未执行完毕之前,调用get()的线程(假定此时是主线程),直到call()方法返回了结果后,此时future.get()才会得到该结果,然后主线程才会切换到runnable状态
- 所以Future是一个存储器,它存储了call()这个任务的结果,然而这个任务的执行时间是无法提前确定的,因为这完全取决于call()方法执行的情况
Future的五个主要方法
常用方法:
-
cancel
方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。
- 如果任务已经完成,则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;
- 如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,
- 若mayInterruptIfRunning设置为false,则返回false;
- 如果任务还没有执行,则无论mayInterruptIfRunning为true还是false,肯定返回true。
-
isCancelled
方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。 -
isDone
方法表示任务是否已经完成,若任务完成,则返回true; -
get()
方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回; -
get(long timeout, TimeUnit unit)
用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。 -
FutureTask
类实现了RunnableFuture
接口,而RunnnableFuture接口继承了Runnable和Future接口,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。 -
FutureTask
可以用来包装Callable或者Runnbale
对象。因为FutureTask
实现了Runnable
接口,所以FutureTask也可以被提交给Executor
get 方法的行为取决于Callable任务的状态,只有以下这 几种情况:
- 任务正常完成:get 方法会立刻返回结果
- 任务尚未完成(任务还没开始或进行中):get将阻塞并指导任务完成
- 任务执行过程中抛出Exception:get方法会排出ExecutionExecption:这里的抛出异常,是call()执行时产生的那个异常,看到这个异常类型是
java.until.concurrent.ExecutionException.
不论call()执行时抛出的异常类型是什么,最后get方法抛出的异常类型都是ExecutionException,
任务被取消:get方法会抛出CallcellationException
- 任务超时:get方法有一个重载方法,是传入一个延迟时间的,如果时间到了还没有获取结果,get方法就会排出
TimeoutExceptionget
get(long timeout,TimeUnit unit) 方法: 超时不获取 用get(long timeout,TimeUnit unit)
方法时,如果call()在规定时间内完成了任务,那么就会正常获取到返回值,如果再制定时间内没有计算出结果,那么就会抛出TimeoutException
超时不获取,任务需取消
Future的基本使用
1、线程池的submit方法返回Future对象,get基本用法
先给线程池提交任务,提交的时候线程池就会返回一个空的Future容器,当线程的任务一但执行完了,就是我们获取执行结果的时候,线程池就会把结果填充到之前的空的Future中(注意不是新创建一个新的Future容器),现在就可以从这个Future中获取任务的执行结果
java
package Future类;
import java.util.Random;
import java.util.concurrent.*;
public class demo11 {
public static void main(String[] args) {
ExecutorService executor= Executors.newFixedThreadPool(10);
Future<Integer> submit = executor.submit(new myCallable());
try {
System.out.println(submit.get()); //1667597655
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}finally {
executor.shutdown();
}
}
}
class myCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt();
}
}
2、多个任务,用Future数组来获取结果
java
package Future类;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;
public class demo222 {
public static void main(String[] args) {
ExecutorService executor= Executors.newFixedThreadPool(2);
//批量的提交任务的时候,用list来批量的接受数据
ArrayList<Future> list=new ArrayList<>();
for (int i = 0; i <20 ; i++) {
Future<Integer> submit = executor.submit(new myCallable());
list.add(submit);
}
for (int i = 0; i < 20; i++) {
Future<Integer> future = list.get(i);
try {
Integer integer = future.get();
System.out.println(integer);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
class myCallable1 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
Thread.sleep(3000);
return new Random().nextInt();
}
}
Future模式的高阶版本------ CompletableFuture
Future模式虽然好用,但也有一个问题,那就是将任务提交给线程后,调用线程并不知道这个任务什么时候执行完,如果执行调用get()方法或者isDone()方法判断,可能会进行不必要的等待,那么系统的吞吐量很难提高。
为了解决这个问题,JDK对Future模式又进行了加强,创建了一个CompletableFuture,它可以理解为Future模式的升级版本,它最大的作用是提供了一个回调机制,可以在任务完成后,自动回调一些后续的处理,这样,整个程序可以把"结果等待"完全给移除了。
typescript
package Future类;
import java.util.concurrent.CompletableFuture;
public class demo33 {
public static void main(String[] args) {
//创建异步执行任务
CompletableFuture.supplyAsync(demo33::getPrice)
//当getPrice()执行完成后,就会自动调用thenAccept()中的函数
.thenAccept(result-> System.out.println("价格为"+result))
//排除异常后调用这个里面的函数
.exceptionally(e->{
e.printStackTrace();
return null;
});
}
static Double getPrice(){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return Math.random()*20;
}
}
首先将getPrice()为
基础创建一个异步调用,然后,使用*thenAccept()
* ,设置一个后续的操作,也就是说getPrice()执行完成后的后续处理。可以很明显的看到,CompletableFuture
比一般的Future更具有实用性,因为它可以在Future执行成功后,自动回调进行下一步的操作,因此整个程序不会有任何阻塞的地方(简单来说就是不用去等待Future的执行,而是让Future执行成功后,自动来告诉你)