File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Another Question (.... Threads / join() ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Another Question (.... Threads / join() )" Watch "Another Question (.... Threads / join() )" New topic

Another Question (.... Threads / join() )

Chris Cairns
Ranch Hand

Joined: Jan 31, 2003
Posts: 48
Could someone, please, explain what the effect of placing a join in the code below will do? Specifically, I'm not sure what the join does.

[ Jess added UBB [code] tags to preserve whitespace, check 'em out! She also added a bit more descriptive title... ]
[ March 11, 2003: Message edited by: Jessica Sant ]
John Hembree
hired gun
Ranch Hand

Joined: Mar 07, 2003
Posts: 250

If I understand it correctly, when you start a program you are executing the main method within the context of a single thread. Then as you create a new Thread object using "MyThread mt1 = new MyThread("mt1");" you are creating a new thread within the processor for executing various code snippets. In the case of this program mt1 and mt2 are both individual threads running along side of the main thread of the program.
mt1.start() and mt2.start() moves the threads into a ready state so that the cpu is now allowed to begin execution on that respective thread(s). These threads are all allowed to run thru to completion independently of each other within the context of the main thread. (Someone smarter than me might have to clarify whether they run within the parent thread or if the parent can die and then new thread continue to live.) Now comes along "mt1.join", this ties execution of the main parent thread to execution of mt1, so mt1 must run thru to completion before the main thread continues and thus starts mt2.
Hopefully I haven't butchered this topic, but I think that's the way it works.
Reshma Shanbhag
Ranch Hand

Joined: Sep 17, 2002
Posts: 204
Most of what u said is right.
yea, the parent thread can die before the chid thread.
For eg;

In the above example, the "main" thread creates a new thread "Thread1". The execution of these two threads are independent of each other. Invoking the start method of the "Thread1", "main" thread runs to completion. while "Thread1"
continues to be alive and gets into running state on obtaining a CPU cycle.
if //line1 is replaced by t.join()(i haven't mentioned the try catch block with the InterruptedException, which is needed), the "main" method dies only after the Thread1 is dead.
Basically the join method waits for the thread to die.

I hope this helps you
[ March 12, 2003: Message edited by: Reshma Pai ]

SCJP 1.4, SCWCD 1.4
I agree. Here's the link:
subject: Another Question (.... Threads / join() )
It's not a secret anymore!