首页  

scala future 实例     所属分类 scala 浏览量 794
注意 import scala.concurrent.ExecutionContext.Implicits.global
不导入 Future创建会报错
No implicit arguments of type: ExecutionContext

需要显示 提供 scala.concurrent.ExecutionContext

object Future extends scala.AnyRef {
  def apply[T](body : => T)(implicit executor : scala.concurrent.ExecutionContext) : scala.concurrent.Future[T]  
  
object ExecutionContext extends scala.AnyRef {
  def fromExecutor(e : java.util.concurrent.Executor) : scala.concurrent.ExecutionContextExecutor  
  
trait ExecutionContextExecutor extends scala.AnyRef with scala.concurrent.ExecutionContext with java.util.concurrent.Executor {


// 创建线程池 用于 future执行
val executor = Executors.newFixedThreadPool(3)
val executionContext = ExecutionContext.fromExecutor(executor)


// 在指定的线程池中运行
val future3 = Future {
  Thread.sleep(1000)
  List("a3", "b3", "c3")
}(executionContext)
    

import java.util.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.Duration import scala.concurrent.{Await, ExecutionContext, Future} object FutureDemo { // 创建线程池 用于 future执行 val executor = Executors.newFixedThreadPool(3) val executionContext = ExecutionContext.fromExecutor(executor) def main(args: Array[String]) { val future = Future { getList() } val future2 = Future { Thread.sleep(2000) List("a2", "b2", "c2") } // 在指定的线程池中运行 val future3 = Future { Thread.sleep(1000) List("a3", "b3", "c3") }(executionContext) println("future=" + future) println("future2=" + future2) // for 多行 用 大括号 val list3Future = for { list1 <- future list2 <- future2 list3 = list1 ++ list2 } yield { // list1 ++ list2 list3 } println("list3Future=" + list3Future) // 等待执行完成 var result = Await.result(list3Future, Duration.Inf) println("result=" + result) println("list3Future.2=" + list3Future) println("list3Future.isCompleted=" + list3Future.isCompleted) list3Future.foreach(println) println("future3=" + future3) } def getList(): List[String] = { Thread.sleep(1000) List("a", "b", "c") } } 也可以这样 val list3Future = for { list1 <- future list2 <- future2 } yield { list1 ++ list2 }
完整代码 https://gitee.com/dyyx/hellocode/blob/master/demo/scala/scalademo/src/main/java/demo2/FutureDemo.scala
scala Future和Promise

上一篇     下一篇
scala 类继承实例

一站式大数据平台StreamX

Spark 累加器 Accumulator

AKKA actor model 的一些思考

Scala 柯里化 Currying

scala 方法和函数的区别