Future模式
- Future的核心思想是:一个耗时的方法,在调用时,立马先返回一个Future,通过Future这个数据结构去控制方法的计算过程。
- 接口
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>
public interface Callable<V> {
V call() throws Exception;
}
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
- 场景:网购厨具 -> 超市购买食材 -> 客户做饭。
- 同步代码:
public class CommonCook {
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
OnlineShopping thread = new OnlineShopping();
thread.start();
thread.join();
Thread.sleep(2000);
Foods foods = new Foods();
System.out.println("第二步:食材到位");
System.out.println("第三步:开始展现厨艺");
cook(thread.kitchenWare, foods);
System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
}
static class OnlineShopping extends Thread {
private KitchenWare kitchenWare;
@Override
public void run() {
System.out.println("第一步:下单");
System.out.println("第一步:等待送货");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第一步:快递送到");
kitchenWare = new KitchenWare();
}
}
static void cook(KitchenWare kitchenWare, Foods foods) {}
static class KitchenWare {}
static class Foods {}
}
第一步:下单
第一步:等待送货
第一步:快递送到
第二步:食材到位
第三步:开始展现厨艺
总共用时7013ms
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureCook {
public static void main(String[] args) throws InterruptedException, ExecutionException {
long startTime = System.currentTimeMillis();
Callable<KitchenWare> onlineShopping = new Callable<KitchenWare>() {
@Override
public KitchenWare call() throws Exception {
System.out.println("第一步:下单");
System.out.println("第一步:等待送货");
Thread.sleep(5000);
System.out.println("第一步:快递送到");
return new KitchenWare();
}
};
FutureTask<KitchenWare> task = new FutureTask<KitchenWare>(onlineShopping);
new Thread(task).start();
Thread.sleep(2000);
Foods foods = new Foods();
System.out.println("第二步:食材到位");
if (!task.isDone()) {
System.out.println("第三步:厨具还没到,心情好就等着(心情不好就调用cancel方法取消订单)");
}
KitchenWare kitchenWare = task.get();
System.out.println("第三步:厨具到位,开始展现厨艺");
cook(kitchenWare, foods);
System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
}
static void cook(KitchenWare kitchenWare, Foods foods) {}
static class KitchenWare {}
static class Foods {}
}
第一步:下单
第一步:等待送货
第二步:食材到位
第三步:厨具还没到,心情好就等着(心情不好就调用cancel方法取消订单)
第一步:快递送到
第三步:厨具到位,开始展现厨艺
总共用时5005ms