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

时间:2013-04-02 19:51:52

标签: 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库中的任何内容吗?

修改

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

4 个答案:

答案 0 :(得分: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

}

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

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

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

答案 1 :(得分:3)

使用the answer of @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)
}

答案 2 :(得分:2)

除了标准并发库之外,还有一些。例如,可以使用com.twitter / util-core库:

val pool = FuturePool.unboundedPool
pool {
   <code>
}

您的示例如下:

Thread.currentThread setName "MyThread"

// because you have to be using a single-threaded one to get the same name
val pool = FuturePool(Executors.newSingleThreadExecutor())

pool {
  Thread.currentThread setName "MySpecialThread"
}

pool {
  println(Thread.currentThread.getName) // MySpecialThread
}

println(Thread.currentThread.getName)

答案 3 :(得分:1)

基于based on the docs&#39; S @EECOLOR,这是一个在一个单独的线程上执行任意代码的通用,可重用的方法:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

def executeParallelTask[T](code: => T): Future[T] = Future(code)