Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread.join() on unstarted thread

 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following program, adapted from a mock exam question, prints "Joining" and then "Joined".

My question: Why doesn't this hang forever after printing the word "Joining"? I've never started thread t, so trying to join it should wait indefinitely.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the source code:

Since isAlive() is false, join() does nothing.
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you never started the Thread:
Thread t = new Thread();
...rest of code elided ...
t.start();
System.out.println( "Joining..." );
t.join();
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that ... I even said it in my question.
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whoops, sorry. You're right. To be less vague, join was made to simply return quietly if the Thread is not started. Since you did not start the thread, it simply does nothing (but now seeing the guy who posted the source code - is that allowed in the license - it's obvious in there)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic