How to run code in a separate thread?

I want to create a thread and run the code in this thread. What are the options in Scala?

A usage example would be something like this:

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

Is there anything in the Scala built-in library that I can use?

Edit

I updated the snippet to better reflect the intention

+5
source share
3 answers

Using @alexwriteshere's answer as the basis, I created this implementation:

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
source

Yes there is. You can use scala.concurrentfrom the standard library. More specifically, you can use futures - very complex asynchronous computing

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

+5

concurrency, . , 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)
+2

All Articles