首页  

scala try future 例子     所属分类 scala 浏览量 260
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration.{Duration, SECONDS}
import scala.util.{Failure, Success, Try}

object TryFutureDemo {

  def main(args: Array[String]) {

    // Try 捕捉异常
    // Failure(java.lang.ArithmeticException: / by zero)
    println(Try(3 / 0))
    println(Try(3).flatMap { x => Try(x + "_hello") })
    // Failure(java.lang.ArithmeticException: / by zero)
    println(Try(3 / 0).flatMap { x => Try(x + "hello") })
    //
    println(Try(3).toOption)
    println(Try(3).map { x => x + 2 })
    println(Try(3 / 0) match {
      case Success(x) => x
      case Failure(e) => -1
    })
    // 异步执行 2秒后 打印hello
    Future {
      Thread.sleep(2000); println("hello")
    }
    println("waiting......")
    Thread.sleep(3000)

    def sayHello(s: String): String = {
      Thread.sleep(1000)
      s + " say hello"
    }

    val f1 = Future(sayHello("cat"))
    val f2 = Future(sayHello("tiger"))

    val futures = Future.sequence(Seq(f1, f2))

    futures.onComplete {
      case result =>
        println("futures.onComplete run")
        result.toOption.foreach(println)
    }
    println("waiting2......")
    Thread.sleep(2000)

    // 同步获取结果 指定时间内返回结果
    val maxTime = Duration(3, SECONDS)
    println(concurrent.Await.result(Future(sayHello("dog")), maxTime))
    // 同步获取结果 超时异常
    val maxTime1 = Duration(1, SECONDS)
    println(concurrent.Await.result(Future(sayHello("fish")), maxTime1))

    Thread.sleep(2000)

  }
}

Failure(java.lang.ArithmeticException: / by zero) Success(3_hello) Failure(java.lang.ArithmeticException: / by zero) Some(3) Success(5) -1 waiting...... hello waiting2...... futures.onComplete run List(cat say hello, tiger say hello) dog say hello Exception in thread "main" java.util.concurrent.TimeoutException: Future timed out after [1 second] at scala.concurrent.impl.Promise$DefaultPromise.tryAwait0(Promise.scala:248) at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:261) at scala.concurrent.Await$.$anonfun$result$1(package.scala:201) at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:62) at scala.concurrent.Await$.result(package.scala:124) at demo.TryFutureDemo$.main(TryFutureDemo.scala:55) at demo.TryFutureDemo.main(TryFutureDemo.scala)
https://gitee.com/dyyx/hellocode/blob/master/demo/scala/scalademo/src/main/java/demo/TryFutureDemo.scala
scala Option Try Either scala Future sequence scala future for 实例 scala future 实例 scala Future和Promise scala Promise

上一篇     下一篇
Reactive Programming

sbt 创建运行 Scala play 项目

scala Option Try Either

scala Play框架 依赖注入 guice 使用说明

sbt自定义任务

scala shell 使用第三方jar包