Joining a stream in Groovy

What does the join method do?
How in:

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

This code works fine even without a join statement.

+7
source share
1 answer

Same as in Java - this causes the thread that calls join be blocked until the thread represented by the Thread object on which join was called was terminated.

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

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

Without join this println can happen while another thread is still running, so you get an old thread , and then two seconds later a new thread . With join main thread must wait until another thread ends, so you will not receive anything in two seconds, then new thread , then old thread .

+18
source

All Articles