Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining Thread in Groovy

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.

like image 868
Evgenij Reznik Avatar asked Jan 16 '13 23:01

Evgenij Reznik


1 Answers

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.

like image 56
Ian Roberts Avatar answered Sep 18 '22 19:09

Ian Roberts