通过Future 异步回调,不阻塞下面的执行,并且在方法最后执行完毕前,调用方法或通过回调的方法获取返回值。
其核心其实就是创建一个线程
这也是多线程的一个设计模式
public interface Future<T> {
T get() throws InterruptedException;
}
这边在方法中添加synchronized
关键字,就是防止多线程问题。
public class AsynFuture<T> implements Future<T>{
private volatile boolean done = false;
private T result;
public void done(T result){
synchronized (this){
this.result = result;
this.done = true;
this.notifyAll();
}
}
@Override
public T get() throws InterruptedException {
synchronized (this){
while(!done){
this.wait();
}
}
return result;
}
}
这个接口看似平平无奇,却是将你的调用逻辑进行了隔离
public interface FutureTask<T> {
T call() throws InterruptedException;
}
建service,实现方法
public class FutureService {
public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer){
AsynFuture asynFuture = new AsynFuture();
// 这里的线程就是整个设计模式的关键,添加变量final Consumer<T> consumer 建立回调
new Thread(() -> {
T result = null;
try {
result = task.call();
} catch (InterruptedException e) {
e.printStackTrace();
}
asynFuture.done(result);
consumer.accept(result);
}).start();
return asynFuture;
}
}
测试类
public static void main(String[] args) throws InterruptedException {
FutureService futureService = new FutureService();
String temp = null;
Future<String> future = futureService.submit(() -> {
Thread.sleep(1000);
return "Finish";
},(a) -> { // 这里把上面代码的Consumer 改成了 Function 函数了。所以不要照搬着看
System.out.println(a + " ===");
return a;
});
// System.out.println("=============");
// System.out.println(future.get());
}