我对Scala很新,正在玩Futures。我有一小段代码,与我在教程中找到的版本略有不同。
object Tmp extends App {
val f = Future {
val r = Random.nextInt(500)
if (r < 499)
throw new RuntimeException("bad value")
r
}
f.onComplete(ff => {
if (ff.isSuccess) {
println(s"success ${ff.get}")
}
})
f.failed.foreach(t => s"failure ${t.getMessage}")
// do the rest of your work
println("A ..."); Thread.sleep(100)
println("B ..."); Thread.sleep(100)
println("C ..."); Thread.sleep(100)
println("D ..."); Thread.sleep(100)
println("E ..."); Thread.sleep(100)
println("F ..."); Thread.sleep(100)
Thread.sleep(1000)
}
每次运行时,输出都是:
A ...
B ...
C ...
D ...
E ...
F ...
我既没有看到代码执行的成功/失败部分
答案 0 :(得分:2)
抛出失败,但您使用if (ff.isSuccess)
忽略它。以下是您应该如何处理onComplete
:
import scala.concurrent.Future
import scala.util.{Failure, Success}
import scala.util.Random
import scala.concurrent.ExecutionContext.Implicits.global
object Tmp extends App {
val f = Future {
val r = Random.nextInt(500)
if (r < 499)
throw new RuntimeException("bad value")
r
}
f onComplete {
case Success(value) => value
case Failure(e) => e.printStackTrace
}
// do the rest of your work
println("A ..."); Thread.sleep(100)
println("B ..."); Thread.sleep(100)
println("C ..."); Thread.sleep(100)
println("D ..."); Thread.sleep(100)
println("E ..."); Thread.sleep(100)
println("F ..."); Thread.sleep(100)
Thread.sleep(1000)
}
答案 1 :(得分:-2)
您的代码会引发异常,因为:
if (r < 499)
throw new RuntimeException("bad value")
你没有看到任何内容
的原因f.failed.foreach(t => s"failure ${t.getMessage}")
是因为你只创建字符串,但不做任何事情。试试这个:
object Tmp extends App {
val f = Future {
val r = Random.nextInt(500)
if (r < 499)
throw new RuntimeException("bad value")
r
}
f.onComplete(ff => {
if (ff.isSuccess) {
println(s"success ${ff.get}")
}
else{ //added this
println(s"failes ${ff.get}")
}
})
f.failed.foreach(t => println(s"failure ${t.getMessage}"))//and added this
// do the rest of your work
println("A ..."); Thread.sleep(100)
println("B ..."); Thread.sleep(100)
println("C ..."); Thread.sleep(100)
println("D ..."); Thread.sleep(100)
println("E ..."); Thread.sleep(100)
println("F ..."); Thread.sleep(100)
Thread.sleep(1000)
}