Scala:线程无法访问线程外的变量?

Scala: thread is unable to access variable outside of thread?

object Test extends App {
  val x = 0
  val threadHello = (1 to 5).map(_ => new Thread(() => {
    println("Hello")
    println(x) // this results in join never resolving "collecting data"
  }))
  threadHello.foreach(_.start())
  threadHello.foreach(_.join())
  println(x)
}

我仍在学习 Scala 中的并发性,但我遇到了一个问题,其中 thread.join() 永远无法解决并且程序永远结束 运行,除非我注释掉 println(x)声明。

调试显示线程永远无法访问 x 的值,我不确定为什么会出现这个问题。

The problem highlighted when debugging in IntelliJ

实际上,您的代码在 Scala 2.13 中对我来说运行得很好。

也就是说,我怀疑您的问题与 scala.Appval 的初始化顺序有关。如果是这样,您应该可以通过 x lazy 来解决它,如下所示:

object Test extends App {
  lazy val x = 0
  val threadHello = (1 to 5).map(_ => new Thread(() => {
    println("Hello")
    println(x) // this results in join never resolving "collecting data"
  }))
  threadHello.foreach(_.start())
  threadHello.foreach(_.join())
  println(x)
}

或者,不要使用 scala.App:

object Main {
  def main(args: Array[String]) {
    val x = 0
    val threadHello = (1 to 5).map(_ => new Thread(() => {
      println("Hello")
      println(x) // this results in join never resolving "collecting data"
    }))
    threadHello.foreach(_.start())
    threadHello.foreach(_.join())
    println(x)
  }
}