7
join
方法有什麼作用?
如:在Groovy中加入線程
def thread = Thread.start { println "new thread" }
thread.join()
此代碼工作正常,即使沒有join
聲明。
join
方法有什麼作用?
如:在Groovy中加入線程
def thread = Thread.start { println "new thread" }
thread.join()
此代碼工作正常,即使沒有join
聲明。
因爲它在Java中的相同 - 它使線程稱爲join
阻塞,直到由在其上join
被稱爲已終止Thread
對象所表示的線程。
如果您讓主線程在產生新線程後執行其他操作(例如println
),您可以看到區別。
def thread = Thread.start {
sleep(2000)
println "new thread"
}
//thread.join()
println "old thread"
沒有join
而另一個線程仍在運行此的println可能發生,所以你會得到old thread
,其次兩秒後通過new thread
。 join
主線程必須等到另一個線程完成後,兩秒鐘內什麼也沒有,然後new thread
,然後old thread
。
所以程序不會做任何事情,直到'線程'完成? – user1170330
@ user1170330我已經添加了更多的示例。 –
非常感謝! – user1170330