• Post Reply Bookmark Topic Watch Topic
  • New Topic

I need to be clear about the join-method in the Thread-class.  RSS feed

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My teacher wrote this comment below and it confuses me: "//This blocks the execution of the current (main) thread from proceeding until the thread has completed." So does that mean that the t2.join()-method is not invoked until the first thread has died?
Are the threads running simultaneously or not? What exactly is happening here? Thanks for your time.


 
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Threads run (at least virtually) in a parallel way.
However if a thread needs to wait until the another runs to completion, Thread.join can be issued.
This call will block the calling thread until the other one (the one to be joined to) finishes.

Is it not described in the API docs?
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sven Sylta wrote:So does that mean that the t2.join()-method is not invoked until the first thread has died?

Yes, that is what it means.

Sven Sylta wrote:Are the threads running simultaneously or not? What exactly is happening here? Thanks for your time.

Yes, threads are running simultaneously. What happens in your code: Two new threads are created and started, and then the main thread first waits for the first one to finish (line 13), and then for the second one to finish (line 14).

join() will return immediately if the thread on which it is called has already finished. So, suppose that the main thread is waiting for t1 to finish in line 13 and in the mean time t2 finishes, then when the main thread reaches line 14 to wait for the second thread, line 14 will immediately return.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sven Sylta wrote:Are the threads running simultaneously or not? What exactly is happening here?

I think the others have covered most of it, but the reason for having join() is that sometimes programs only need some of their logic to be multi-threaded, and join() provides a "sync-point" so the master thread knows that everything that it launched in parallel has completed; at which point it might then be able to launch into another multi-threaded phase...

Winston

BTW: Please DontWriteLongLines. It makes your post very hard to read. I've broken yours up this time, but for future reference:
80 characters max/line.
and that inludes String literals AND comments. Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!