What does the join
method do?
As in:
def thread = Thread.start { println \"new thread\" }
thread.join()
This code works fine e
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
.