我想生成一个线程并在该线程中运行代码。 Scala 中有哪些选项?
示例用法如下所示:
Thread.currentThread setName "MyThread"
val myThreadExecutor = ???
val threadNamePromise = Promise[String]
future {
myThreadExecutor run {
val threadName = "MySpecialThread"
Thread.currentThread setName threadName
threadNamePromise success threadName
}
}
Await.result(threadNamePromise.future, Duration.Inf)
future {
myThreadExecutor run {
println(Thread.currentThread.getName) // MySpecialThread
}
}
future {
myThreadExecutor run {
println(Thread.currentThread.getName) // MySpecialThread
}
}
println(Thread.currentThread.getName) // MyThread
我可以使用内置 Scala 库中的任何内容吗?
编辑
我更新了片段以更好地反射(reflect)意图
最佳答案
就在这里。您可以使用 scala.concurrent
来自标准库。更具体地说,您可以使用 future - 高度可组合的异步计算。
import java.util.concurrent.Executors
import concurrent.{ExecutionContext, Await, Future}
import concurrent.duration._
object Main extends App {
// single threaded execution context
implicit val context = ExecutionContext.fromExecutor(Executors.newSingleThreadExecutor())
val f = Future {
println("Running asynchronously on another thread")
}
f.onComplete { _ =>
println("Running when the future completes")
}
Await.ready(f, 5.seconds) // block synchronously for this future to complete
}
Futures 在执行上下文中运行,这是线程池的抽象。此上下文可以隐式传递。在上面的例子中,我们使用了一个全局的,由 Scala 库定义 - 但是你可以通过分配许多执行上下文来控制程序的这一方面。
该代码段仅执行您的要求 - 同时运行代码。然而, future 远不止于此——它们允许您异步计算值,组合多个 future 以获得它们之间的依赖关系或并行的结果。
这是一个介绍:http://docs.scala-lang.org/overviews/core/futures.html
关于scala - 如何在单独的线程中运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773123/