像下面这样实现的未来是否会获得一个新线程?显然不是(见下面的输出)。为什么?如果我希望我的代码在新线程上运行,我应该怎么做?
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])
成功的未来
(main123,Thread[run-main-0,5,run-main-group-0])