代码:
package org.learningconcurrency.ch3
/**
* Created by kaiyin on 1/17/16.
*/
import scala.concurrent._
import scala.concurrent.forkjoin.ForkJoinPool
import org.learningconcurrency.log
object Ch3 {
val executor = new ForkJoinPool()
val executor1 = ExecutionContext.global
def execute(body: => Unit) = ExecutionContext.global.execute(new Runnable {
override def run(): Unit = body
})
def main(args: Array[String]) {
executor.execute(new Runnable {
override def run(): Unit = {
log("Task run.")
}
})
executor1.execute(new Runnable {
override def run(): Unit = log("Running")
})
execute {
log("hello")
}
// log("hello")
}
}
如果我在intellij中运行它(在mac上按ctrl + shift + R),它什么都不打印。但是,一旦我取消注释主函数中的最后一行,一切都会突然发挥作用:
main: hello
ForkJoinPool-2-worker-13: hello
ForkJoinPool-1-worker-13: Task run.
ForkJoinPool-2-worker-15: Running
为什么?
Github回复:https://github.com/kindlychung/learnConcurrentScala
斯卡拉:2.11.7 Intellij 15.0.2 sbt:0.13.8
答案 0 :(得分:1)
主线程在其他线程完成之前完成。您有两种解决方案可以解决这个问题:
如果是遗嘱执行人,请致电'关闭'方法,然后等待终止'等待线程完成然后关闭执行程序的方法。