scala 中 Future 的简单使用

孤街醉人 提交于 2020-11-08 04:19:04

scala Future

object MyFuture {

  def doWork(i: Int): Int = {
    Thread.sleep(3 * 1000)
    i
  }

  def main(args: Array[String]): Unit =
    1 to 5 foreach { i =>
      val future = Future {
        blocking {
          doWork(i)
        }
      }
      future onComplete {
        case Success(value) => println(value)
        case Failure(exception) => println(exception)
      }
      // 通过视界转换,让 Int 拥有更丰富的方法
      // 由于继承了 AnyVal,表明这是一个 value class
      /*
      implicit final class DurationInt(private val n: Int) extends AnyVal with DurationConversions {
        override protected def durationIn(unit: TimeUnit): FiniteDuration = Duration(n.toLong, unit)
      }
       */
      Await.result(future, 7 seconds)
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!