Scala Future OnComplete调用 笔记

来源:互联网 发布:python sock.recv 编辑:程序博客网 时间:2024/05/22 04:49

在并发Future中建立API调用,和主线程并发地执行任务

  /*  调用远程API,获得传入城市的温度   */  def cityTemp(name:String):Double = {    val url = "http://api.openweathermap.org/data/2.5/weather"    val cityUrl = s"$url?q=$name&APPID=981224145dabaaf57b51ff469e7f1acd"    val json = io.Source.fromURL(cityUrl).mkString    val pattern = """.*"temp":([\d]+).*""".r    val pattern(temp) = json    temp.toDouble  }

import concurrent.Futureimport concurrent.ExecutionContext.Implicits.globalimport scala.util.Success  def main(args:Array[String]):Unit = {    //调用Future.sequence 并发执行Future    val cityTemps:Future[Seq[Double]] = Future sequence Seq(      Future(cityTemp("Fresno")),Future(cityTemp("Tempe"))    )    //Future回调函数,当Future执行完成,会自动调用这个函数,输出函数结果    cityTemps onComplete {      case Success(Seq(x, y)) if x > y => println(s"Fresno is warmer: $x K")      case Success(Seq(x, y)) if y > x => println(s"Tempo is warmer: $y K")    }    //OnComplete调用对变量的影响    var temp = 0.0d;    cityTemps onComplete {      case Success(Seq(x, y)) if x > y => temp = x      case Success(Seq(x, y)) if y > x => temp = y    }    //主线程继续执行,为了看到OnComplete的执行结果,等待10秒    //temp before complete: 0.0   println("temp before complete: " + temp)    Thread.sleep(10000)    //temp after complete: 294.0    println("temp after complete: " + temp)    println("result complete")  }


 
原创粉丝点击