gpt4 book ai didi

scala - 回调中的 future 在同一线程中运行

转载 作者:行者123 更新时间:2023-12-02 01:55:50 26 4
gpt4 key购买 nike

当我运行这段代码时:

val intList = List(1, 6, 8)

val listOfFutures = intList.map{
i => future {
println("future " +i)
Thread.sleep(i* 1000)
if (i == 12)
throw new Exception("6 is not legal.")
i
}

}
val futureOfList = Future.sequence(listOfFutures)

futureOfList onSuccess{
case int => {
logInfo("onSuccess")
int.foreach(i => {
Future{
logInfo("h : " + i)
}
})
}
}

futureOfList onFailure{
case int => {
logInfo("onFailure")
}
}

logInfo("after")

嵌套的 futures 都在同一个线程中运行:

future 1
2013/11/24 11:55:00.002 [ModelUtilsTest] [main]: INFO: [] after
future 6
future 8
2013/11/24 11:55:14.878 [ModelUtilsTest] [ForkJoinPool-1-worker-1]: INFO: [] onSuccess
2013/11/24 11:55:15.378 [ModelUtilsTest] [ForkJoinPool-1-worker-1]: INFO: [] h : 1
2013/11/24 11:55:15.378 [ModelUtilsTest] [ForkJoinPool-1-worker-1]: INFO: [] h : 6
2013/11/24 11:55:15.378 [ModelUtilsTest] [ForkJoinPool-1-worker-1]: INFO: [] h : 8

为什么会这样?我需要内在的 future 并行运行。

最佳答案

Future 实现检查它是否要在拥有当前线程的 ForkJoinPool 上运行某些东西。在这种情况下,它将 ForkJoinTask.fork(),将新的工作单元添加到当前工作线程的工作队列中。任何其他线程都必须窃取该工作才能执行它。您不会期望在可用线程上看到任务的均匀分布,尤其是琐碎的任务。

在接下来的运行中,worker-9首当其冲:

scala> val f = Future sequence (1 to 20 map (i => Future(i)))
f: scala.concurrent.Future[scala.collection.immutable.IndexedSeq[Int]] = scala.concurrent.impl.Promise$DefaultPromise@47fe4ff8

scala> f onSuccess { case is => is foreach (i => Future(println(s"$i on ${Thread.currentThread}"))) }

scala> 2 on Thread[ForkJoinPool-1-worker-9,5,main]
5 on Thread[ForkJoinPool-1-worker-15,5,main]
4 on Thread[ForkJoinPool-1-worker-3,5,main]
6 on Thread[ForkJoinPool-1-worker-9,5,main]
1 on Thread[ForkJoinPool-1-worker-5,5,main]
12 on Thread[ForkJoinPool-1-worker-7,5,main]
11 on Thread[ForkJoinPool-1-worker-9,5,main]
15 on Thread[ForkJoinPool-1-worker-9,5,main]
16 on Thread[ForkJoinPool-1-worker-9,5,main]
17 on Thread[ForkJoinPool-1-worker-9,5,main]
18 on Thread[ForkJoinPool-1-worker-9,5,main]
19 on Thread[ForkJoinPool-1-worker-9,5,main]
20 on Thread[ForkJoinPool-1-worker-9,5,main]
3 on Thread[ForkJoinPool-1-worker-1,5,main]
10 on Thread[ForkJoinPool-1-worker-13,5,main]
9 on Thread[ForkJoinPool-1-worker-11,5,main]
8 on Thread[ForkJoinPool-1-worker-3,5,main]
7 on Thread[ForkJoinPool-1-worker-15,5,main]
14 on Thread[ForkJoinPool-1-worker-7,5,main]
13 on Thread[ForkJoinPool-1-worker-5,5,main]

关于scala - 回调中的 future 在同一线程中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20174300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com