File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Printing sequence - Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Printing sequence - Threads" Watch "Printing sequence - Threads" New topic

Printing sequence - Threads

Sen George
Ranch Hand

Joined: Sep 21, 2005
Posts: 76
In the following code,

the output got is 'In doIt method' followed by ' Thread is running.'

I was expecting the output in reverse- ' Thread is running.' followed by ' In doIt method'. Could someone please clarify this behavior?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The Thread.start() method returns pretty much immediately, but it takes some time for a thread to get going. The thread that called start() (i.e., your main thread) keeps running while the newly-created thread gets ready to go. By the time that new thread starts actually running Java code, the original thread will have executed many instructions.

So the main thread here calls start(), then immediately calls doIt(), which prints a message. All the while, the new thread is being initialized. Finally, some time after doit() is called, the new thread starts to execute your code.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Printing sequence - Threads
It's not a secret anymore!