我正在使用CompletableFuture和Java 8中的流,每次运行时都会得到不同的打印输出。只是好奇,为什么?
public class DoIt {
public static class My {
private long cur = 0;
public long next() {
return cur++;
}
}
public static long add() {
long sum = 0;
for (long i=0; i<=100;i++) {
sum += i;
}
return sum;
}
public static long getResult(CompletableFuture<Long> f) {
long l = 0;
try {
f.complete(42l);
l = f.get();
System.out.println(l);
} catch (Exception e) {
//...
}
return l;
}
public static void main(String[] args){
ExecutorService exec = Executors.newFixedThreadPool(2);
My my = new My();
long sum = Stream.generate(my::next).limit(20000).
map(x -> CompletableFuture.supplyAsync(()-> add(), exec)).
mapToLong(f->getResult(f)).sum();
System.out.println(sum);
exec.shutdown();
}
}
如果我跳过f.complete(42l)调用,我总会得到相同的结果。
答案 0 :(得分:1)
http://download.java.net/jdk8/docs/api/java/util/concurrent/CompletableFuture.html#complete-T-
发生complete(42l)
来电时,某些add()
可能已经完成。