The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes join()?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "join()??" Watch "join()??" New topic


srikanth reddy
Ranch Hand

Joined: Jul 28, 2005
Posts: 252


what my doubt is here calling join means that the main thread will have to wait until the Thread T1 has finished which is not i thought that there should be no Output..but it gives End..will it not wait forever??

Thanks & Regards<br /> <br />-Srikanth
M Jairam

Joined: Nov 04, 2005
Posts: 22
1. Note that t1.join(); says that put the current thread on hold until thread t1 has finished.
2. In your example, t1 thread does not even exist - thread only exist after a call to its start() method.

To see join() in action, I have just made slight change to your program. Try it with and without the t1.join();. You will then see how join() works.

Hope this helps.

class TechnoSample {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(getRunnable(20, "t1"));
Thread t2 = new Thread(getRunnable(10, "t2"));

public static Runnable getRunnable(final int id, final String name){
return new Runnable(){
public void run(){
for(int i = 0; i < id; i++){
System.out.print(name+i + " ");

Kevin Lam
Ranch Hand

Joined: Oct 27, 2005
Posts: 68
How about if main() just call join() but not t.join()? what does that mean?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

There is no (static) join() method so that won't even compile. You can only join on a thread object (well, also on DatagramSocketImpl, but that's not what is meant here ).

How To Ask Questions How To Answer Questions
Kevin Lam
Ranch Hand

Joined: Oct 27, 2005
Posts: 68
I see

But what about within the Runnable object, it calls join() without referencing to other threads?

Rob Spoor

Joined: Oct 27, 2005
Posts: 20279

Where does it do that?? It could only do that if the Runnable is also a Thread.

If you try to join on the same thread (like Thread.currentThread.join()) you would get deadlock - it is waiting for itself to end, which it will never do because it is waiting.
Henry Wong

Joined: Sep 28, 2004
Posts: 20538

There is no black magic happening here. All the join() method does is call the isAlive() method. And if it is alive, it will just call the wait() method. This repeats until the thread is no longer alive.

And BTW, notification is sent by the cleanup code for the thread.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: join()??
It's not a secret anymore!