加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:52:37 所属栏目:安全 来源:网络整理
导读:我想生成一个线程并在该线程中运行代码. Scala有哪些选项? 示例用法如下: Thread.currentThread setName "MyThread"val myThreadExecutor = ???val threadNamePromise = Promise[String]future { myThreadExecutor run { val threadName = "MySpecialThrea
我想生成一个线程并在该线程中运行代码. 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库中的任何内容吗?

编辑

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

解决方法

就在这里.您可以使用标准库中的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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读