| Author |
How Thread.sleep works...
|
Dale DeMott
Ranch Hand
Joined: Nov 02, 2000
Posts: 514
|
|
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
|
By failing to prepare, you are preparing to fail.<br />Benjamin Franklin (1706 - 1790)
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16487
|
|
The API documentation for that method says this: "Causes the currently executing thread to sleep..." Does that answer your question?
|
 |
Dale DeMott
Ranch Hand
Joined: Nov 02, 2000
Posts: 514
|
|
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
Bartender
Joined: Aug 07, 2007
Posts: 1217
|
|
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
Joined: Jan 30, 2000
Posts: 18670
|
|
[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 ]
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: How Thread.sleep works...
|
|
|