在Groovy中加入主题 [英] Joining Thread in Groovy
问题描述
加入
方法是做什么的?
如:
What does the join
method do?
As in:
def thread = Thread.start { println "new thread" }
thread.join()
即使没有 join
语句,这段代码也可以正常工作。
This code works fine even without the join
statement.
推荐答案
与Java中的相同 - 它会导致 连接
的线程阻塞,直到线程
被调用的 join
对象已终止。
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.
您可以在产生新线程后让主线程执行其他操作(例如, println
),以查看区别。
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"
没有加入
这个println会在另一个线程仍在运行时发生,所以你会得到 old thread
,两秒后由新线程
。使用 join
时,主线程必须等到其他线程完成后,才能在两秒内得到任何内容,然后 new 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
.
这篇关于在Groovy中加入主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!