| Author |
Calling Sleep with and without instance Query
|
Mohit G Gupta
Ranch Hand
Joined: May 18, 2010
Posts: 634
|
|
sleep is a static method of thread class
let there be a Thread t
what does line 1 and line2 do....
Do line 1 causes the Thread t to sleep ?
Do line 2 also does the same thing ?
|
OCPJP 6.0 93%
OCPJWCD 5.0 98%
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
|
Calling a static method on an instance of the class is same as calling it using the class name. So the call to t.sleep(2000) at line 2 is the same as Thread.sleep(2000)...
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
The code won't do anything since is doesn't compile because of 3 different reasons.
Then that is fixed it will cause the thread to sleep (execute nothing). Like Ankit said you can invoke static methods through an reference to an instance.
However this is not recommended because when you change the reference type (anyone got a better name for reference type?) you'll invoke a different static method.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Mohit G Gupta
Ranch Hand
Joined: May 18, 2010
Posts: 634
|
|
Calling a static method on an instance of the class is same as calling it using the class name. So the call to t.sleep(2000) at line 2 is the same as Thread.sleep(2000)...
so t.sleep and Thread.sleep would cause the newly created thread to sleep
|
 |
Rohit Ramachandran
Ranch Hand
Joined: Oct 05, 2010
Posts: 102
|
|
|
Compile error because you didn't enclose the second sleep in a try catch.
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
Mohit, what does the javadocs for sleep method say?? I believe it says
Causes the currently executing thread to sleep
So it basically sleeps the thread which calls it. Period...
|
 |
Gari Jain
Ranch Hand
Joined: Jun 29, 2009
Posts: 100
|
|
t.sleep() is same as Thread.sleep()-will put the thread in current execution to sleep.
don't get confused by code which seems to call sleep on some other thread instance.
--will put to sleep the current thread in execution only because anotherThread.sleep(); is same as Thread.sleep();
|
OCPJP 6-100%; Preparing for GATE11
|
 |
Mohit G Gupta
Ranch Hand
Joined: May 18, 2010
Posts: 634
|
|
Thread anotherThread at=new Thread(--runnable object--);
anotherThread.sleep();
If the following code is in main method
then,
would cause the main Thread to sleep and not the anotherThread
But if same code was in run method of anotherThread,then
would cause the anotherThread to sleep and not the main Thread
Am i right ?
|
 |
 |
|
|
subject: Calling Sleep with and without instance Query
|
|
|