scala - 如何在单独的线程中运行代码?

标签 scala

我想生成一个线程并在该线程中运行代码。 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/

相关文章:

scala - 如何过滤 sbt 监视更改的文件?

scala - Spark 数据帧 : does groupBy after orderBy maintain that order?

scala - 测试有序无限流是否包含值

git - 如何从我的 sbt 自动增加版本号并上传到 git

scala - 如何使用 Akka Streams 在分隔符上拆分入站流

Scala REPL 在 Ubuntu 上不起作用

scala - 如何将 List[zio.Task[List[A]]] 转换为 zio.Task[[List[A]]

scala - 通用 scala 函数,其输入是变量 arity 的函数

Scala:在模式匹配中混合特征和案例类

scala - 在类中包装 akka actor 会导致内存泄漏吗?