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

EEC*_*LOR 6 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
Run Code Online (Sandbox Code Playgroud)

我可以使用内置Scala库中的任何内容吗?

编辑

我更新了代码段以更好地反映意图

Mar*_*ila 5

就在这里.您可以使用scala.concurrent标准库中的.更具体地说,您可以使用期货 - 高度可组合的异步计算

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 { result =>
    println("Running when the future completes")
  }

  Await.ready(f, 5.seconds) // block synchronously for this future to complete

}
Run Code Online (Sandbox Code Playgroud)

期货在执行上下文中运行,执行上下文是线程池的抽象.可以隐式传递此上下文.在上面的示例中,我们使用了由Scala库定义的全局 - 但您可以通过分配许多执行上下文来控制程序的这个方面.

该片段仅执行您所要求的内容 - 同时运行代码.然而,期货远不止于此 - 它们允许您异步计算值,组合多个期货以获得具有它们之间的依赖关系的结果,或者并行.

这是一个介绍:http://docs.scala-lang.org/overviews/core/futures.html


EEC*_*LOR 3

使用@alexwriteshere 的答案作为基础,我创建了这个实现:

import java.util.concurrent.Executors
import scala.concurrent.future
import scala.concurrent.JavaConversions.asExecutionContext

class ApplicationThread {
  protected implicit val context = 
    asExecutionContext(Executors.newSingleThreadExecutor())

  def run(code: => Unit) = future(code)
}
Run Code Online (Sandbox Code Playgroud)

更新

感谢@Dth 指出这是现代版本:

import java.util.concurrent.Executors
import scala.concurrent.future
import scala.concurrent.JavaConversions.asExecutionContext

class ApplicationThread {
  protected implicit val context = 
    asExecutionContext(Executors.newSingleThreadExecutor())

  def run(code: => Unit) = future(code)
}
Run Code Online (Sandbox Code Playgroud)