Scala并发之 Future ExecutionContext
所属分类 scala
浏览量 690
Java java.util.concurrent
scala scala.concurrent
Future ExecutionContext
Future 提供回调函数 避免阻塞
Future 两种状态
未完成
已完成 有返回值 或者 异常 ,Future完成后不可变
Future object apply 创建 Future
def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] = impl.Future(body)
需要 ExecutionContext 或者 隐式提供
import scala.concurrent.ExecutionContext.Implicits.global
val future = Future[Int] {
Thread.sleep(1000)
1
}
回调函数
onComplete onFailure onSuccess
future.onComplete {
case Success(result) => println(result)
case Failure(e) => println("error: " + e.getMessage)
}
future.onSuccess {
case num => println(num)
}
future.onFailure {
case e => println(e.getMessage)
}
ExecutionContext与Java中的线程池类似,用来管理线程
Java中 利用 Executors来定义线程池ExecutorService
newFixedThreadPool newSingleThreadExecutor newCachedThreadPool newScheduledThreadPool
ExecutionContext.fromExecutorService
def fromExecutorService(e : java.util.concurrent.ExecutorService) : scala.concurrent.ExecutionContextExecutorService = { ... }
val executor = Executors.newFixedThreadPool(3)
val executionContext = ExecutionContext.fromExecutor(executor)
scala future 实例
scala future for 实例
scala Future sequence
java并发包JUC简介
java线程池系列文章汇总
上一篇
下一篇
scala future for 实例
scala Future sequence
scala Promise
scala type 关键字
Scala 抽象类(abstract) 和 特质(trait) 异同
typesafe config 读取配置