Scala future 回调函数方法

16 篇文章 0 订阅
7 篇文章 0 订阅

object FuturesCallbacks extends App {
  import scala.concurrent._
  import ExecutionContext.Implicits.global
  import scala.io.Source

  def getUrlSpec(): Future[Seq[String]] = Future {
    val f = Source.fromURL("http://www.w3.org/Addressing/URL/url-spec.txt")
    try f.getLines.toList finally f.close()
  }

  val urlSpec: Future[Seq[String]] = getUrlSpec()

  def find(lines: Seq[String], word: String) = lines.zipWithIndex collect {
    case (line, n) if line.contains(word) => (n, line)
  } mkString("\n")

  urlSpec foreach {
    lines => log(s"Found occurrences of 'telnet'\n${find(lines, "telnet")}\n")
  }

  urlSpec foreach {
    lines => log(s"Found occurrences of 'password'\n${find(lines, "password")}\n")
  }

  log("callbacks installed, continuing with other work")

}



 

结果输出:

[info] Running org.learningconcurrency.ch4.FuturesCallbacks
run-main-0: callbacks installed, continuing with other work
[success] Total time: 4 s, completed 2016-3-20 9:21:34
> ForkJoinPool-1-worker-3: Found occurrences of 'telnet'
(207,  telnet , rlogin and tn3270 )
(745,                         nntpaddress | prosperoaddress | telnetaddress
(806,  telnetaddress           t e l n e t : / / login )
(931,   for a given protocol (for example,  CR and LF characters for telnet

ForkJoinPool-1-worker-5: Found occurrences of 'password'
(107,                         servers). The password, is present, follows)
(109,                         the user name and optional password are)
(111,                         user of user name and passwords which are)
(222,      User name and password)
(225,   password for those systems which do not use the anonymous FTP)
(226,   convention. The default, however, if no user or password is)
(234,   is "anonymous" and the password the user's Internet-style mail)
(240,   currently vary in their treatment of the anonymous password.  )
(816,  login                   [ user [ : password ] @ ] hostport )
(844,  password                alphanum2 [ password ] )
(938,   The use of URLs containing passwords is clearly unwise. )





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值