我的Intellij工作表不会打印出Thread.run中定义的数字序列,但sbt会这样做

问题描述 投票:1回答:1

我在Intellij工作表中尝试了以下代码:

val hello = new Thread(new Runnable {
  def run() {
    for (i<-1 to 10) print(i,",")
  }
})
hello.start()

我得到的输出是

hello: Thread = Thread[Thread-111,5,main]

我希望也会得到类似“1 2 3 ... 10”的东西。为什么我的Intellij不打印数字序列?以下是我的Intellij截图。

enter image description here

非常令人惊讶的是,如果我在sbt控制台中输入相同的代码,我得到了结果:

scala> val hello = new Thread(new Runnable {
     |   def run() {
     |     for (i<-1 to 10) print(i,",")
     |   }
     | })
hello: Thread = Thread[Thread-5,5,run-main-group-0]

scala> hello.start()
(1,,)(2,,)(3,,)(4,,)(5,,)(6,,)(7,,)(8,,)(9,,)(10,,)
scala>
multithreading scala intellij-idea
1个回答
2
投票

有两个问题:

  1. 你的代码不会等到线程完成
  2. print将参数视为元组并打印:(1 ,,)(2 ,,)(3 ,,)(4 ,,)(5 ,,)(6 ,,)(7 ,,)(8 ,,)( 9日)(10日)

这样的东西应该工作(我没有尝试运行IntelliJ,只是在Scala控制台中

scala> :paste
// Entering paste mode (ctrl-D to finish)

val hello = new Thread(new Runnable {
  def run() {
    println((1 to 10).mkString(","))
  }
})
hello.start()
hello.join()

// Exiting paste mode, now interpreting.

1,2,3,4,5,6,7,8,9,10
hello: java.lang.Thread = Thread[Thread-10,5,]

scala>
© www.soinside.com 2019 - 2024. All rights reserved.