| Author |
Doubt related to sleep() in Thread
|
Jolly Tiwari
Ranch Hand
Joined: Mar 26, 2006
Posts: 77
|
|
Hi! All, I have a doubt related to static sleep() method in Thread class. if we have a code snippet like ... . public static void main(String...s) { MyRunnable mr=new MyRunnable(); Thread t1=new Thread(mr); t1.start(); t1.sleep(40000); } ... ... ... As sleep is a static method ,so reference of user created thread (t1) will be used to retrieve the class name i.e Thread class and in that case the currently running thread ,which is the main thread will go to sleep if main thread is currently executing even we had called sleep() in thread t1. Please tell me what actually goes on in this scenario. Regards Jolly
|
 |
Sunny Jain
Ranch Hand
Joined: Jul 23, 2007
Posts: 433
|
|
I think, You are right..I think it will be decided at the compile time that which method is to be called. This code is equivalent to following: public static void main(String...s) { MyRunnable mr=new MyRunnable(); Thread t1= null; //t1.start(); --> To avoid null pointer exception t1.sleep(40000); } I think this code will work and in this case it will cause main thread to sleep, Same applies to your code also. I will curious to know the exact answer and will keep eye on this post.
|
Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
Please use CODE tags when you post code.
public static void main(String...s) { MyRunnable mr=new MyRunnable(); Thread t1=new Thread(mr); t1.start(); t1.sleep(40000); }
This code will not compile since you did not handle the InterrptedException. The sleep method is invoked natively. Which means that java uses native code to figure out how to sleep, which makes sense in a lot of ways. You will have to grab the native implementation to figure out whats going on
|
SCJP 6 articles - SCJP 5/6 mock exams - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by Jolly tiw: ...the currently running thread ,which is the main thread will go to sleep if main thread is currently executing even we had called sleep() in thread t1...
That's exactly right!
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
 |
|
|
subject: Doubt related to sleep() in Thread
|
|
|