Scala 学习笔记之集合(8) Try和Future

import util._
import concurrent.ExecutionContext.Implicits.global
import concurrent.Future
import concurrent.duration._

object CollectionDemo9 {
  def main(args: Array[String]): Unit = {
    //Try捕捉异常
    println(Try(10 / 0))
    println(Try(10).flatMap { x => Try(x + "abc") })
    println(Try(10 / 0).flatMap { x => Try(x + "abc") })
    //会丢Exception
    println(Try(10).toOption)
    println(Try(10).map { x => x + 2 })
    println(Try(10 / 0) match {
      case Success(x) => x
      case Failure(error) => -1
    })
    //Future使用, 异步5秒后会打印hi
    Future { Thread.sleep(3000); println("hi") }
    println("waiting")
    Thread.sleep(5000)

    //异步执行Future, 并用回调函数获得结果
    def sayHello(s: String): String = {
      Thread.sleep(3000)
      s + " call Future"
    }
    val futureCaller = Future sequence Seq(Future(sayHello("sky")), Future(sayHello("bill")))
    futureCaller onSuccess {
      case Seq(x, y) => println(x + "," + y)
    }
    println("waiting again")
    Thread.sleep(5000)
    
    //同步调用Future, 如果在指定时间异步调用返回结果,则返回结果。
    val maxTime = Duration(10, SECONDS)
    println(concurrent.Await.result(Future(sayHello("sky")), maxTime))
    //同步调用Future, 如果在指定时间异步调用没有返回结果,则抛出异常。
    val maxTime1 = Duration(2, SECONDS)
    println(concurrent.Await.result(Future(sayHello("sky")), maxTime1))

  }
}

运行结果:

Failure(java.lang.ArithmeticException: / by zero)
Success(10abc)
Failure(java.lang.ArithmeticException: / by zero)
Some(10)
Success(12)
-1
waiting
hi
waiting again
sky call Future,bill call Future
sky call Future
Exception in thread "main" java.util.concurrent.TimeoutException: Futures timed out after [2 seconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223)
at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:107)
at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
at scala.concurrent.Await$.result(package.scala:107)
at com.citi.scala.CollectionDemo9$.main(CollectionDemo9.scala:43)
at com.citi.scala.CollectionDemo9.main(CollectionDemo9.scala)

转载于:https://www.cnblogs.com/AK47Sonic/p/7096716.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值