scala Future sequence
所属分类 scala
浏览量 730
scala.concurrent.Future#sequence
Useful for reducing many Futures into a single Future.
收集 Future 执行结果,通过 foreach 取出收集结果并进行后续处理
import java.time.LocalDateTime
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
object FutureSequenceDemo {
def main(args: Array[String]) {
val f1 = Future {
Thread.sleep(2000)
println("Future1.time=" + LocalDateTime.now().toString())
println("Future1.currentThread=" + Thread.currentThread().getName)
"a"
}
val f2 = Future {
Thread.sleep(1000)
println("Future2.time=" + LocalDateTime.now().toString())
println("Future2.currentThread=" + Thread.currentThread().getName)
"b"
}
// Future[List[String]]
val f3 = Future.sequence(List(f1, f2))
f3.foreach(println)
println("time1=" + LocalDateTime.now())
println("f3=" + f3)
println("time2=" + LocalDateTime.now())
Thread.sleep(3000)
println("f3.2=" + f3)
}
}
time1=2022-02-14T12:32:27.126
f3=Future(< not completed >)
time2=2022-02-14T12:32:27.129
Future1.time=2022-02-14T12:32:28.056
Future1.currentThread=ForkJoinPool-1-worker-13
Future2.time=2022-02-14T12:32:29.055
Future2.currentThread=ForkJoinPool-1-worker-11
List(a, b)
f3.2=Future(Success(List(a, b)))
上一篇
下一篇
scala 学的走火入魔
spark 广播变量
scala future for 实例
scala Promise
Scala并发之 Future ExecutionContext
scala type 关键字