Joining Thread in Groovy

旧街凉风 提交于 2020-01-01 08:39:28

问题


What does the join method do?
As in:

def thread = Thread.start { println "new thread" }
thread.join()

This code works fine even without the join statement.


回答1:


The same as it does in Java - it causes the thread that called join to block until the thread represented by the Thread object on which join was called has terminated.

You can see the difference if you make the main thread do something else (e.g. a println) after spawning the new thread.

def thread = Thread.start {
  sleep(2000)
  println "new thread"
}
//thread.join()
println "old thread"

Without the join this println can happen while the other thread is still running, so you'll get old thread, followed two seconds later by new thread. With the join the main thread must wait until the other thread has finished, so you'll get nothing for two seconds, then new thread, then old thread.



来源:https://stackoverflow.com/questions/14370076/joining-thread-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!