Scala 2.10中的可能的错误:期货不运行

我正在尝试重现新的 Scala 2.10 futures feature的例子.
我使用的代码是:

import scala.concurrent.Future
import scala.concurrent.future

object Test {
    def main(args: Array[String]) {
     println("Test print before future")
     val s = "Hello"
     val f = future {s + " future!"}
     f onSuccess {case v => println(v)}
     println("Test print after future")
    }
}

而不是打印:

Test print before future
Hello future!
Test print after future

它只是打印:

Test print before future
Test print after future

任何想法为什么我有这个行为?我的scala编译器版本是2.10.0-20120507.

解决方法

问题是,您正在将其作为独立程序执行,其主线程在其中一个工作线程可以执行“Hello future!”之前终止.的println. (新的期货图书馆产生的线程是守护进程线程).

您还可以使用Await对象(也可在scala.concurrent中)等待,直到将来f完成:

import scala.concurrent._
import scala.concurrent.util._

object Test {
  def main(args: Array[String]) {
    println("Test print before future")

    val s = "Hello"
    val f = future {s + " future!"}
    f onSuccess {case v => println(v)}
    println("Test print after future")

    Await.ready(f,Duration.Inf)
  }
}

这可以打印:

Test print before future
Test print after future
Hello future!

或者,可以打印“你好未来!”之前“根据线程安排测试打印”.

同样,您可以强制主线程等待,直到f在最后一个println之前完成,如下所示:

import scala.concurrent._
import scala.concurrent.util._

object Test {
  def main(args: Array[String]) {
    println("Test print before future")

    val s = "Hello"
    val f = future {s + " future!"}
    f onSuccess {case v => println(v)}

    Await.ready(f,Duration.Inf)        

    println("Test print after future")
  }
}

哪个打印:

Test print before future
Hello future!
Test print after future

但是,请注意,当您使用等待时,您将被阻止.这当然是确保您的主应用程序线程不终止,但一般不应该使用,除非另有要求.

(Await对象是一个这样的情况下必需的转义窗口,但是在整个应用程序代码中使用它而不用担心其语义可能会导致执行速度更慢,执行速度更慢.如果需要确保回调以某种特定的顺序执行,例如,还有其他的替代方法,例如“未来”的“和”和“方法”).

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...