为什么Scala用于理解运行未来的函数? [英] Why Scala for comprehension run Future functions sequentially?

查看:157
本文介绍了为什么Scala用于理解运行未来的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._

object FutureFor {
  def getA(n: Int) = {
    val x: Future[String] = Future {
      println("I'm getA")
      for (i <- 1 to 5) {
        println(".")
        Thread.sleep(200)
      }
      s"A$n"
    }
    x
  }

  def getB(n: Int) = {
    val x: Future[String] = Future {
      println("I'm getB")
      for (i <- 1 to 5) {
        println(".")
        Thread.sleep(200)
      }
      s"B$n"
    }
    x
  }

  def main(args: Array[String]) = {

    println("\nThis is sequential")
    val rs1 = for {
      a <- getA(1)
      b <- getB(1)
    } yield (a + b)
    println(Await.result(rs1, 1 minute))

    println("\nThis is concurrent")
    val first = getA(2)
    val second = getB(2)
    val rs2 = for {
      a <- first
      b <- second
    } yield (a + b)

    println(Await.result(rs2, 1 minute))
  }

}

此代码的输出是:

This is sequential
I'm getA
.
.
.
.
.
I'm getB
.
.
.
.
.
A1B1

This is concurrent
I'm getB
.
I'm getA
.
.
.
.
.
.
.
.
.
A2B2

但是我认为在这两种情况下,Future都应该同时执行。

However I would think that in both the cases the Future should execute concurrently. What is it that is making the execution sequential in the first case?

推荐答案

它依次执行,因为 getB c> getA 返回的未来的回调函数中将不会调用 。在这里解释得很好。

It executes sequentially because getB won't be called but only in the callback function of the Future returned by getA. It's explained very well here.

更新:因此 for 解析转换为 map flatMap s和过滤器,它们只是在后台变成回调

update: so the for comprehension translates to maps, flatMaps and filters, which on they turn are just turned into callbacks behind the scenes

这篇关于为什么Scala用于理解运行未来的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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