- 先解释使用场景: 在多线程时,使用继承Thread类,或实现Runnable接口创建线程类,重写run()方法,方法中调用需要多线程处理的代码,执行时调用start() 方法,但是会发现一个问题,run()方法没有返回值,假设逻辑代码执行完毕后需要返回值怎么办
- 通过实现 Callable 接口创建线程类,Callable接口中的泛型就是返回值类型,重写接口中的call()方法,该方法就相当于前面的run()方法,不同的是可以返回线程执行完毕后需要的数据
- 会将返回值封装为一个Future类型的数据
- 只要不去获取子线程中的数据,在调用该子线程的方法的后续处理是不会阻塞等待的
- Future模式的常用方法:
get() 获取返回数据,
boolean isDone() 获取是否执行完毕,不管是否有返回值,只要执行完毕都会返回true
boolean isCanceller() 如果任务完成前,被取消,则返回true
boolean cancel(boolean b) 取消任务执行,如果任务还没执行返回false,如果方法已经执行通过该方法传递true取消成功 返回true,如果方法以及执行完毕,再去传递true,由于已经执行完毕不能再取消了返回false
使用示例
- 自定义线程类,实现Callable接口,重写call() 返回
class TestCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("下载中");
Thread.sleep(3000L);
return "下载完毕";
}
}
- 运行测试,注意,使用Thread运行Callable中的线程方法,与使用线程池运行Callable中的线程方法
public class MyTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1.创建有返回值的线程类
TestCallable testCallable = new TestCallable();
//2.创建 FutureTask 包装线程类
FutureTask futureTask = new FutureTask<>(testCallable);
//3.通过 Thread 运行有返回值的线程类
new Thread(futureTask).start();
System.out.println("主线程运行---注意只要没有获取子线程返回的结果,当前主线程是不会阻塞等待的");
//获取TestCallable线程执行结果
String resykt = (String) futureTask.get();
//通过线程池执行Callable线程示例
ExecutorService service = Executors.newCachedThreadPool();
Future<String> future = service.submit(testCallable);
String str = future.get();
System.out.println(str);
}
}
Future 原理
自己理解的是跟线程通讯有点像,有两个线程A与B,假设B线程执行完毕后有返回结果,B线程中添加用来存储结果的属性,添加用来标识是否存储完毕的属性,run方法执行完毕后要对存储结果数据的属性赋值,修改标识为完毕状态,调用notify()方法获取锁池中休眠的线程,提供获取执行结果数据的方法,方法中首先判断是否添加完毕,如果没有则调用wait() 方法,进入释放锁并进入等待状态
- 自定义Future
class MyFuture{
public String result; //存储结果数据
public boolean flag = false; //标识是否结果是否设置完毕
//模拟线程方法执行逻辑代码
public synchronized void myRun() {
System.out.println("线程B执行");
if(flag){
return;
}
try {
Thread.sleep(5000L);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("线程B执行完毕");
result = "success";
flag = true;
//设置完毕当前释放锁,唤醒锁池中其它线程
notify();
}
//获取结果方法
public synchronized String getResult() throws InterruptedException {
while (!flag){
System.out.println("线程B未返回结果进入休眠状态");
//结果未设置完毕当前进入等待状态
wait();
}
return result;
}
}
2.调用测试
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建自定义Future对象
MyFuture myFuture = new MyFuture();
//通过在线程类的run方法中调用自定义Future,模拟多线程执行
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
myFuture.myRun();
}
});
//线程执行
thread.start();
System.out.println("线程A执行");
//获取结果数据
System.out.println(myFuture.getResult());
}