在Windows 7上播放2.4。 我是Scala / Play框架中的新手,我有如下操作:
def delay = Action.async { request =>
println(new Date() + "-1-" + Thread.currentThread().getId)
val delayed = play.api.libs.concurrent.Promise.timeout("Delayed", 10.seconds)
println(new Date() + "-2-" + Thread.currentThread().getId)
val result = delayed.map{
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(_)
}
println(new Date() + "-4-" + Thread.currentThread().getId)
result
}
我希望执行顺序应为1,2,4,3。但是输出是1,2,3,4并且都在同一个线程中。然后我改变代码,替换
val result = delayed.map{
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(_)
}
带
val result = delayed.map{ message =>
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(message)
}
然后输出是1,2,4,3,并且3在不同的线程中。
有人可以告诉我原因吗?谢谢!
答案 0 :(得分:1)
让我们稍微重构一下代码。第一个:
// The code between the braces here is just a code block. It is
// executed immediately to calculate the value of mappingFunction.
// That is before the assignment to mappingFunction.
val mappingFunction = {
println(new Date() + "-3-" + Thread.currentThread().getId)
{ message: String => Ok(message) }
}
val result = delayed.map(mappingFunction)
第二个:
// The code between the braces here is the function that will
// be executed when the future is completed. In which thread it
// will be executed depends on the execution context, and is not
// guaranteed to be the one where mappingFunction is defined.
val mappingFunction = { message: String =>
println(new Date() + "-3-" + Thread.currentThread().getId)
Ok(message)
}
val result = delayed.map(mappingFunction)