11.1 Future接口
Future接口的一般用法
假设某业务逻辑有三个“计算”逻辑:
- 购买煎饼果子(要等待好久);
- 购买已装杯的豆浆(很快);
- 乘班车上班(绝对不能错过)。
同步编程就是:
- 购买煎饼果子;
- 完成步骤1后,再购买已装杯的豆浆;
- 完成步骤2后,再乘班车上班。
假设步骤1的时间不定,而班车发车时间是固定的,那极有可能错过班车。
异步编程就是:
- 给老板说一声购买煎饼果子,稍后来取;
- 不等拿到煎饼果子,就去购买已装杯的豆浆;
- 完成步骤2后,看看赶班车还剩多少时间,假设还剩10分钟,那就等煎饼果子10分钟,如果10分钟后还没有轮到我,那就不要了,直接上班车。
import java.util.concurrent.ThreadFactory;
public class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
}
import java.util.concurrent.*;
public class FutureMain {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool(new MyThreadFactory());
Future<Double> future = executor.submit(new Callable<Double>() {
@Override
public Double call() throws Exception {
return doSomeLongComputation();
}
});
doSomethingElse();
try {
Double result = future.get(1, TimeUnit.SECONDS);
} catch (ExecutionException ee) {
// 计算过程中抛出一个异常
} catch (InterruptedException ie) {
// 当前线程在等待过程中被中断
} catch (TimeoutException te) {
// 在Future对象完成之前超过已过期
}
}
private static Double doSomeLongComputation() {
System.out.println("进入doSomeLongComputation()");
return 9527D;
}
private static void doSomethingElse() {
System.out.println("进入doSomethingElse()");
}
}
上述代码展示了Future接口异步计算的一般用法。
CompletableFuture接口的一般用法
仅等待Future集合中最快结束的任务完成,并返回它的结果
@Test
public void testAnyOf() {
long start = System.nanoTime();
CompletableFuture<String> stringFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
System.out.println("###### stringFuture结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "String";
});
CompletableFuture<Integer> intFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(5000);
System.out.println("###### intFuture结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
});
try {
Object early = CompletableFuture.anyOf(stringFuture, intFuture).get();
System.out.println("###### early=" + early);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
long duration = (System.nanoTime() - start) / 1_000_000;
System.out.println("Done in " + duration + " msecs"); // 3秒左右
}