首页  

scala future for 实例     所属分类 scala 浏览量 661
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._

val f1 = Future{ 
Thread.sleep(3000)
println("Future1.time="+java.time.LocalDateTime.now().toString())
println("Future1.currentThread="+Thread.currentThread().getName)
1 + 2
 }
val f2 = Future{ 
Thread.sleep(5000)
println("Future2.time="+java.time.LocalDateTime.now().toString())
println("Future2.currentThread="+Thread.currentThread().getName)

3 + 4 
}
for {
    v1 <- f1
    v2 <- f2
}{
    println("time1="+java.time.LocalDateTime.now().toString())
    println("currentThread1="+Thread.currentThread().getName)
    
    println(v1 + v2) // 10
    println("time2="+java.time.LocalDateTime.now().toString())
    println("currentThread2="+Thread.currentThread().getName)
       
}


代码复制到 scala shell 运行 输出结果 Future1.time=2022-02-14T08:52:01.060 Future1.currentThread=scala-execution-context-global-20 Future2.time=2022-02-14T08:52:03.247 Future2.currentThread=scala-execution-context-global-21 time1=2022-02-14T08:52:03.247 currentThread1=scala-execution-context-global-21 10 time2=2022-02-14T08:52:03.247 currentThread2=scala-execution-context-global-21 放到 main里运行 记得最后 sleep 下 ,否则 main线程 结束后 ,程序退出 ,看不到输出 Future1.time=2022-02-14T08:50:17.352 Future1.currentThread=ForkJoinPool-1-worker-13 Future2.time=2022-02-14T08:50:19.293 Future2.currentThread=ForkJoinPool-1-worker-11 time1=2022-02-14T08:50:19.294 currentThread1=ForkJoinPool-1-worker-11 10 time2=2022-02-14T08:50:19.294 currentThread2=ForkJoinPool-1-worker-11 https://gitee.com/dyyx/hellocode/blob/master/demo/scala/scalademo/src/main/java/demo/FutureForDemo.scala

上一篇     下一篇
scala 方法和函数的区别

scala 学的走火入魔

spark 广播变量

scala Future sequence

scala Promise

Scala并发之 Future ExecutionContext