码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-30 00:05:52      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:lock   app   ons   div   ring   match   捕捉异常   回调   返回结果   

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)

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

标签:lock   app   ons   div   ring   match   捕捉异常   回调   返回结果   

原文地址:http://www.cnblogs.com/AK47Sonic/p/7096716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!