Scala ProcessLogger和未来:如何确保在onComplete块之前调用所有行回调? [英] Scala ProcessLogger & Future: How can I make sure all line callbacks are called BEFORE the onComplete block?
问题描述
import scala.sys.process._
import scala.concurrent._ // (future)
import ExecutionContext.Implicits.global // (future)
/* run "ls /opt"
* which outputs 2 lines:
* - "X11"
* - "local"
*/
val command = Process(Seq("ls", "/opt"), None, "LANG" -> "")
val process = command.run(ProcessLogger(line => {
Thread.sleep(1000) // slow execution down
println(Thread.currentThread)
println(line)
println("")
}))
Future {
process.exitValue // blocks until the process exits
}.onComplete { results =>
println(Thread.currentThread)
println("process exited: after last line callback finished?")
println("DONE")
}
输出(按预期顺序排列 ,但是总是这样吗?):
Output (order as expected, but is this always the case?):
Thread[Thread-47,5,run-main-group-0]
LINE X11
Thread[Thread-47,5,run-main-group-0]
LINE local
Thread[ForkJoinPool-1-worker-3,5,run-main-group-0]
process exited: after last line callback finished?
DONE
似乎还可以。因为 onComplete
块在与行相关的输出完全结束之后输出其文本 。但是,总是这样吗?谁确保不同的线程一个接一个地运行? 我可以依靠这个假定的顺序吗?
It seems o.k. because the onComplete
block outputs its text after line-related output is completely over. But is this always the case? Who makes sure the different threads are run one after the other? Can I rely on this supposed order?
推荐答案
未来是持有某个值的对象,该值可能在
某个时候可用。此值通常是其他
计算的结果:
A Future is an object holding a value which may become available at some point. This value is usually the result of some other computation:
- 如果该计算尚未完成,则说Future未完成。
- 如果计算已完成,但有值或异常,则表示未来已完成。
完成可以采用以下两种形式之一:
Completion can take one of two forms:
-
当Future以某个值完成时,我们说Future以该值成功完成了。
When a Future is completed with a value, we say that the future was successfully completed with that value.
当Future完成计算并抛出异常时,我们说Future失败了。
When a Future is completed with an exception thrown by the computation, we say that the Future was failed with that exception.
创建future对象的最简单方法是调用future方法,该方法将启动异步计算并返回保存结果的future该计算。将来完成后,结果将变为可用。
The simplest way to create a future object is to invoke the future method which starts an asynchronous computation and returns a future holding the result of that computation. The result becomes available once the future completes.
请注意,Future [T]是表示将来对象的类型,而future是一种创建和调度异步计算然后返回的方法。
Note that Future[T] is a type which denotes future objects, whereas future is a method which creates and schedules an asynchronous computation, and then returns a future object which will be completed with the result of that computation.
您可以在 github
这篇关于Scala ProcessLogger和未来:如何确保在onComplete块之前调用所有行回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!