在Groovy中加入Thread

use*_*330 11 concurrency groovy multithreading

join方法有什么作用?
如:

def thread = Thread.start { println "new thread" }
thread.join()
Run Code Online (Sandbox Code Playgroud)

即使没有join声明,此代码也能正常工作.

Ian*_*rts 24

与Java中的相同 - 它会导致调用 join的线程阻塞,直到调用Thread对象所表示的线程join终止.

如果println在生成新线程后让主线程执行其他操作(例如a ),则可以看到差异.

def thread = Thread.start {
  sleep(2000)
  println "new thread"
}
//thread.join()
println "old thread"
Run Code Online (Sandbox Code Playgroud)

没有join这个println可能会发生,而另一个线程仍在运行,所以你会得到old thread,然后两秒钟后new thread.随着join主线程必须等待,直到另一个线程完成,所以你两秒钟得到什么,然后new thread,然后old thread.