在日常生活中,会经常遇到这样的例子,当某一件事情特别耗时,我们往往不会在原地等待,而是利用等待的时间去做其他事情。例如,需要定做一个生日蛋糕,我们只会去蛋糕店和师傅说一声,交完钱拿到票据,然后做自己的事情,过一段时间,拿着刚才的票据,就能拿到蛋糕了。多线程中也存在这样的模式,称之为future模式。
现在,简单的实现这样的模式。
首先定一个Future接口,这个接口只有一个get方法,用来获取结果。
public interface Future<T> {
T get() throws InterruptedException;
}
定义FutureTask接口,这个接口用来抽象执行任务的具体逻辑。
public interface FutureTask<T> {
T call();
}
定义AsyncFutureTask类,实现Future接口,实现get方法,当任务没有完成时调用get方法时,该方法wait
public class AsyncFutureTask<T> implements Future<T> {
private volatile boolean isDone;
private T result;
@Override
public T get() throws InterruptedException {
synchronized (this) {
while (!isDone) {
this.wait();
}
return result;
}
}
public void done(T result) {
synchronized (this) {
isDone = true;
this.result = result;
this.notifyAll();
}
}
}
定义FutureService类,提供submit方法,将具体任务逻辑提交,这里开一个新的线程去执行该逻辑,保证不会阻塞。
public <T> Future<T> submit(FutureTask<T> task) {
AsyncFutureTask<T> asyncFutureTask = new AsyncFutureTask<>();
new Thread(() -> {
asyncFutureTask.done(task.call());
}).start();
return asyncFutureTask;
}
测试类
public class FutureTest {
public static void main(String[] args) throws InterruptedException {
FutureService service = new FutureService();
Future<String> future = service.submit(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "done";
});
System.out.println("============");
System.out.println(future.get());
}
}
结果
============
done
Process finished with exit code 0
实现了future模式