aspose file tools*
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
Author

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
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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]
 
 
subject: Printing sequence - Threads