• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Printing sequence - Threads

 
Sen George
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic