Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How Thread.sleep works...

 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok... lets say I'm executing through a thread and I'm looking to make a thread sleep for say 2 seconds. I put in the following line...

Thread.sleep(2000);

Given that the sleep method is static, how does the class know what specific thread to sleep on? Does it pass along the process id?

TIA
 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API documentation for that method says this:

"Causes the currently executing thread to sleep..."

Does that answer your question?
 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hehe.. I guess. Wasn't sure how it knew what thread was executing however I guess I'll trust the API like I usually do. It must pass something behind the scenes in order to figure out what thread is executing since there is no thread you pass in and the method is static.
 
Tony Docherty
Saloon Keeper
Posts: 3144
72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dale DeMott:
It must pass something behind the scenes in order to figure out what thread is executing since there is no thread you pass in and the method is static.
Not quite true, the current thread is the thread that is executing the sleep method. You don't need to pass a reference to it into the method as it's already there eg it's the thread that's doing the work.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[I wrote this before seeing Tony's response - Jim]

To put it another way - whatever thread is executing the code that called this method is the one that's currently executing at the moment the method is executed. So whatever thread calls sleep, that's the one that sleeps.

Also, note that there's another static method

Thread.currentThread()

Thus, it's always possible to discover the currently-executing thread. There's no extra data that needs to be passed around. It's part of the built-in capabilities of the JVM, implemented via native code. The JVM already has to have a thread scheduler capable of keeping track of multiple threads and letting each one run in turn - and as long as they have that, then it's relatively trivial to provide a method to identify which thread is currently running.
[ August 07, 2007: Message edited by: Jim Yingst ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!