import scala.concurrent.Promise
import scala.util.{Failure, Success}
/**
*
* @author zhangap
* @version 1.0, 2020/7/15
*
*/
object TestFuture {
def main(args: Array[String]): Unit = {
//TODO trySuccess情況一: 如果promise還未完成,則接受傳遞的值尘奏,并返回true
printPromise(testTrySuccess1())
//TODO trySuccess情況二: 如果promise已經(jīng)完成,則忽略傳遞的值府适,并返回false
testTrySuccess2(printPromise)
//TODO tryFailure情況一: 如果promise還未完成族铆,則接受傳遞的值,并返回true
testTryFailure1(printPromise)
//TODO tryFailure情況一: 如果promise已經(jīng)完成,則忽略傳遞的值秦躯,并返回false
testTryFailure2(printPromise)
}
private def testTryFailure2(callback: Promise[Any] => Unit): Unit = {
val p = Promise[Any]
p.failure(new RuntimeException("execfailure"))
println(p.tryFailure(new RuntimeException("tryFailure")))
callback(p)
}
private def testTryFailure1(callback: Promise[Any] => Unit): Unit = {
val p = Promise[Any]
println(p.tryFailure(new RuntimeException("tryFailure")))
callback(p)
}
private def testTrySuccess1(): Promise[Any] = {
val p = Promise[Any]
println(p.trySuccess("trySuccess"))
p
}
private def testTrySuccess2(callback: Promise[Any] => Unit): Unit = {
val p = Promise[Any]
p.success("finish")
println(p.trySuccess("trySuccess"))
callback(p)
}
private def printPromise(promise: Promise[Any]): Unit = {
import scala.concurrent.ExecutionContext.Implicits.global
promise.future.onComplete {
case Success(value) => println(s"success:$value")
case Failure(exception) => exception.printStackTrace()
}
}
}
運(yùn)行結(jié)果