为什么Future.sequence以并行而不是串行的方式执行我的期货? [英] Why Future.sequence executes my futures in parallel rather than in series?

查看:195
本文介绍了为什么Future.sequence以并行而不是串行的方式执行我的期货?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"顺序"一词是指一个一系列一个接一个的动作.

The word "sequence" means a series of actions one after the other.

object Test {

  def main(args: Array[String]) {

    def producer() = {
      val list = Seq(
          future { println("startFirst"); Thread.sleep(3000); println("stopFirst") }, 
          future { println("startSecond"); Thread.sleep(1000); println("stopSecond") }
      )
      Future.sequence(list)
    }

   Await.result(producer, Duration.Inf)
  }
}

因此,我希望该程序能够打印: startFirst stopFirst startSecond stopSecond

Therefore I expect this program to print: startFirst stopFirst startSecond stopSecond

甚至: startSecond stopSecond startFirst stopFirst

or even: startSecond stopSecond startFirst stopFirst

但不是(发生): startFirst startSecond stopSecond stopFirst

but not (as it happens): startFirst startSecond stopSecond stopFirst

为什么不将此方法称为Future.parallel()? 我该怎么使用以保证期货Seq中的所有期货都是串行触发的(而不是并行触发)?

Why this method is not called Future.parallel()? And what should I use to guarantee that all futures in a Seq of futures are triggered serially (as opposed to in parallel) ?

推荐答案

期货同时运行,因为它们是同时启动的:). 要顺序运行它们,您需要使用flatMap:

The futures are running concurrently because they have been started concurrently :). To run them sequentially you need to use flatMap:

Future { println("startFirst"); 
         Thread.sleep(3000); 
         println("stopFirst") 
        }.flatMap{
         _ =>  Future { 
                       println("startSecond"); 
                       Thread.sleep(1000); 
                       println("stopSecond") 
               }
        }

Future.sequence只是转为Seq[Future[T]] => Future[Seq[T]],这意味着收集所有已经开始的期货的结果并将其放在将来.

Future.sequence just turns Seq[Future[T]] => Future[Seq[T]] which means gather results of all already started futures and put it in future .

这篇关于为什么Future.sequence以并行而不是串行的方式执行我的期货?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆