【问题标题】:vavr's Future don't execute some code, with method andThenvavr 的 Future 不执行某些代码,使用方法 andThen
【发布时间】:2018-06-28 20:04:09
【问题描述】:

在这段代码中,我有两种使用 vavr 库的方法。从这个库中,我使用 Future 和方法,然后,这个方法在未来完成时运行,这是同步的,但是当线程调用这个方法中的方法“printTime”时,所有程序都停止了,测试是成功。 这是方法

    public void printTime(String m){
    String pattern = "HH:mm:ss:SSS";
    SimpleDateFormat formato = new SimpleDateFormat(pattern);
    Date date = new Date();
    String dateString = formato.format(date);
    String retorno = dateString+" "+m;
    System.out.println(retorno);
}

这就是测试

    @Test
public void futuroAndThen() {
    Future<String> f1 = Future.of(()->"Julian");
    Future<String> f2 = Future.of(()->"Carvajal");
    Future<String> f3 = Future.of(()->"Montoya");

    Future<String> fResult = f3.andThen(x-> {
        System.out.println(x.get());
        System.out.println(Thread.currentThread().getName());
        printTime("andThen2"+Thread.currentThread().getName());
    }).andThen(y->{
        System.out.println("y:"+y.get());
        System.out.println(Thread.currentThread().getName());
        f2.andThen(x->{
            System.out.println("f2: "+x.get());
            System.out.println("thread f2 "+Thread.currentThread().getName());
        });
        printTime("andThen2"+Thread.currentThread().getName());
    });

}

最后在 printTime 方法中的结果是:

Montoya
pool-1-thread-3
y:Montoya
pool-1-thread-1
f2: Carvajal
thread f2 pool-1-thread-3

和用的方法是:

Montoya
pool-1-thread-1

但有时控制台是空的。

非常感谢:)

【问题讨论】:

  • 你的意思是说:“最终结果没有 [the]方法printTime ...”?
  • 另外:您采取了哪些步骤来解决问题或追查问题的根源?你有没有例如尝试单独运行printTime

标签: java multithreading future vavr vavr-test


【解决方案1】:

您的测试完成,主 JUnit 运行线程在 Future 完成之前退出 JVM。这就是您在控制台上得到不一致结果的原因,这完全取决于 Futures 的执行时间,从 vavr 0.9.2 开始,这发生在 cached thread pool 中。

如果要同步等待Future完成,可以使用

fResult = fResult.await();

在测试结束时。然后您的测试将等待 Future 实例完成,您的输出将是:

Montoya
pool-1-thread-4
23:56:59:570 andThen2pool-1-thread-4
y:Montoya
pool-1-thread-3
f2: Carvajal
thread f2 pool-1-thread-4
23:56:59:572 andThen2pool-1-thread-3

【讨论】:

  • 也就是说printTime方法还没有结束但是主线程是的?
  • 是的,这意味着负责异步解析Future的线程在测试方法结束时由于VM关闭而停止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-23
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多