Joining Thread in Groovy

后端 未结 1 916
南旧
南旧 2021-02-20 01:00

What does the join method do?
As in:

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

This code works fine e

相关标签:
1条回答
  • 2021-02-20 01:36

    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.

    0 讨论(0)
提交回复
热议问题