【发布时间】:2019-04-07 23:04:45
【问题描述】:
这里我们有SeqPar 对象,它包含一个task 例程,它是一个简单的模拟Future,它打印出一些调试信息并返回Future[Int] 类型。
问题是:为什么experiment1允许并行运行,而experiment2总是顺序运行?
object SeqPar {
def experiment1: Int = {
val f1 = task(1)
val f2 = task(2)
val f3 = task(3)
val computation = for {
r1 <- f1
r2 <- f2
r3 <- f3
} yield (r1 + r2 + r3)
Await.result(computation, Duration.Inf)
}
def experiment2: Int = {
val computation = for {
r1 <- task(1)
r2 <- task(2)
r3 <- task(3)
} yield (r1 + r2 + r3)
Await.result(computation, Duration.Inf)
}
def task(i: Int): Future[Int] = {
Future {
println(s"task=$i thread=${Thread.currentThread().getId} time=${System.currentTimeMillis()}")
i * i
}
}
}
当我运行 experiment1 时,它会打印出来:
task=3 thread=24 time=1541326607613
task=1 thread=22 time=1541326607613
task=2 thread=21 time=1541326607613
而experiment2:
task=1 thread=21 time=1541326610653
task=2 thread=20 time=1541326610653
task=3 thread=21 time=1541326610654
观察到差异的原因是什么?我确实知道for 理解像f1.flatMap(r1 => f2.flatMap(r2 => f3.map(r3 => r1 + r2 + r3))) 一样脱糖,但我仍然错过了为什么一个允许并行运行而另一个不允许并行运行的一点。
【问题讨论】:
-
这能回答你的问题吗? Scala's "for comprehension" with futures
标签: scala concurrency parallel-processing future