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

时间:2018-03-04 21:50:29

标签: multithreading scala intellij-idea

我在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]

我希望也会得到像&#34; 1 2 3 ... 10&#34;。为什么我的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>

1 个答案:

答案 0 :(得分:2)

有两个问题:

  1. 您的代码不会等到线程完成
  2. print treats 参数作为元组并打印: (1 ,,)(2 ,,)(3 ,,)(4 ,,)(5 ,,)(6 ,,)(7 ,,)(8 ,,)(9 ,,)(10日)
  3. 这样的东西应该可行(我没有尝试运行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>