gpt4 book ai didi

scala - Future 是否有新线程?

转载 作者:行者123 更新时间:2023-12-05 03:11:58 24 4
gpt4 key购买 nike

像下面这样实现的 future 是否有新线程?显然不是(见下面的输出)。为什么?如果我希望我的代码在新线程上运行,我应该怎么做?

package MyTest

import com.twitter.util._

import scala.language.postfixOps

object Test {

def test1 = Future {
println("BeforeTest", Thread.currentThread())
Thread.sleep(5000)
println("AfterTest", Thread.currentThread())
}

def test2 = test1 onSuccess { case _ => println("Future on success") }

def main(args: Array[String]): Unit = {

println("main", Thread.currentThread())
test2
println("main123", Thread.currentThread())
}
}

输出:

(main,Thread[run-main-0,5,run-main-group-0])

(BeforeTest,Thread[run-main-0,5,run-main-group-0])

(AfterTest,Thread[run-main-0,5,run-main-group-0])

成功的 future

(main123,Thread[run-main-0,5,run-main-group-0])

最佳答案

您使用的是 Twitter future ,而不是 Scala future 。默认情况下,Twitter future 不是多线程的。你必须使用 FuturePool (使用您选择的线程池将其传递给 ExecutorService)

未经测试的示例(我希望足够简单:)):

val executor = Executors.newFixedThreadPool(4)
val pool = FuturePool(executor)

def test1 = pool {
println("BeforeTest", Thread.currentThread())
Thread.sleep(5000)
println("AfterTest", Thread.currentThread())
}

def test2 = test1 onSuccess { case _ => println("Future on success") }

def main(args: Array[String]): Unit = {

println("main", Thread.currentThread())
test2
println("main123", Thread.currentThread())

executor.shutdown()
}

关于scala - Future 是否有新线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com