Created
May 13, 2015 08:02
-
-
Save hanfeisun/9f2a486f0c7f75d67ac3 to your computer and use it in GitHub Desktop.
HowScalaFutureWorksAdvance.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
val is = 1 to 10 toList | |
def db = s"${Thread.currentThread}" | |
def f(i: Int) = { | |
val a = Future { | |
println(db + s" -> \t I'm ${i} -> \t I start to sleep") | |
Thread.sleep(1 * 1000) | |
println(db + s" -> \t I'm ${i} -> \t I wake from sleep") | |
i * 100 | |
}.map { | |
x => | |
println(db + s" => \t I'm ${x} => \t I start to sleep") | |
Thread.sleep(1 * 1000) | |
println(db + s" => \t I'm ${x} => \t I wake from sleep") | |
i * 100 | |
} | |
println(db + s" \t >>> \t I'm in the scope of f(${i})") | |
a.map { | |
x => | |
println(db + s" ~> \t I'm ${x} ~> \t I start to sleep") | |
Thread.sleep(1 * 1000) | |
println(db + s" ~> \t I'm ${x} ~> \t I wake from sleep") | |
i * 100 | |
} | |
println(db + s" \t >>> \t I'm in the end of f(${i})") | |
a | |
} | |
val theFuture = Future.traverse(is)(f _) | |
Await.result(theFuture, 100.seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output on my computer