來自node.js背景,我是Scala的新手,我嘗試使用Twitter的Future.collect來執行一些簡單的併發操作。但是我的代碼顯示了順序行爲而不是併發行爲。我究竟做錯了什麼?Twitter的Future.collect不能同時工作(Scala)
這裏是我的代碼,
import com.twitter.util.Future
def waitForSeconds(seconds: Int, container:String): Future[String] = Future[String] {
Thread.sleep(seconds*1000)
println(container + ": done waiting for " + seconds + " seconds")
container + " :done waiting for " + seconds + " seconds"
}
def mainFunction:String = {
val allTasks = Future.collect(Seq(waitForSeconds(1, "All"), waitForSeconds(3, "All"), waitForSeconds(2, "All")))
val singleTask = waitForSeconds(1, "Single")
allTasks onSuccess { res =>
println("All tasks succeeded with result " + res)
}
singleTask onSuccess { res =>
println("Single task succeeded with result " + res)
}
"Function Complete"
}
println(mainFunction)
,這是輸出我得到的,
All: done waiting for 1 seconds
All: done waiting for 3 seconds
All: done waiting for 2 seconds
Single: done waiting for 1 seconds
All tasks succeeded with result ArraySeq(All :done waiting for 1 seconds, All :done waiting for 3 seconds, All :done waiting for 2 seconds)
Single task succeeded with result Single :done waiting for 1 seconds
Function Complete
我想到的是輸出,
All: done waiting for 1 seconds
Single: done waiting for 1 seconds
All: done waiting for 2 seconds
All: done waiting for 3 seconds
All tasks succeeded with result ArraySeq(All :done waiting for 1 seconds, All :done waiting for 3 seconds, All :done waiting for 2 seconds)
Single task succeeded with result Single :done waiting for 1 seconds
Function Complete
那麼'Future'的整個點就是將計算卸載到另一個線程。因此,在mainFunction的第一行中,將產生三個新線程,這些線程(當生成的線程完成時)會產生另一個線程來執行oncomplete函數。 在第二行中,生成另一個線程,並將與其他線程並行執行。所以我認爲實際產出似乎有效... – irundaia