【问题标题】:Why different result each run?为什么每次运行结果都不一样?
【发布时间】:2013-12-05 20:18:58
【问题描述】:

我正在使用 Java 8 中的 CompletableFuture 和流,每次运行时都会得到不同的打印输出。只是好奇,为什么?

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) 调用,我总是会得到相同的结果。

【问题讨论】:

  • @guido,请搜索现有标签而不是创建新标签。我们已经有一个标签来涵盖 Java 8 Stream API。
  • @Charles 抱歉,Charles,我确实搜索了一个,但没想到 java- 前缀,感谢您的编辑。我现在也找到了streams-ap i(看起来拼写错误)我会在meta上搜索

标签: java-8 java-stream


【解决方案1】:

http://download.java.net/jdk8/docs/api/java/util/concurrent/CompletableFuture.html#complete-T-

complete(42l) 调用发生时,一些add() 可能已经完成。

【讨论】:

  • 好的,错过了那一行。谢谢!
  • @user2685400 如果这个答案对你有帮助,请接受。这就是堆栈溢出的工作方式。参加游览:stackoverflow.com/tour
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多