Causes
the currently executing thread to sleep (temporarily cease execution)
for the specified number of time
A
sleeping thread does not use any processor cycles because its
execution is suspended for the specified duration.
Thread
API provides 2 Methods to make a thread to sleep
public static void
sleep(long millis) throws InterruptedException
public static void
sleep(long millis, int nanos) throws InterruptedException
sleep
method throws InterruptedExceiption, If a sleeping thread interrupted
, it throws Interrupted Exception. Will see more details in the
Interrupts section.
public
static void sleep(long millis) throws InterruptedException
Causes
the currently executing thread to sleep (temporarily cease execution)
for the specified number of milliseconds, subject to the precision
and accuracy of system timers and schedulers. The thread does not
lose ownership of any monitors. Will discuss about acquiring abut
monitor in synchronization topic
public
static void sleep(long millis, int nanos) throws InterruptedException
Causes
the currently executing thread to sleep (cease execution) for the
specified number of milliseconds plus the specified number of
nanoseconds. The thread does not lose ownership of any monitors.
Better don't depend on nano seconds, they are depend on the
underlying system Architecture.
sleep
is a static method, so we have to call by class name.
You
must handle the Interrupted Exception, otherwise compiler will throw
error.
Example
class MyThread implements Runnable{ public void run(){ System.out.println("About to call sleep method"); Thread.sleep(1000); System.out.println("sleep time finished"); } public static void main(String args[]){ MyThread task = new MyThread(); Thread t1 = new Thread(task); t1.start(); } }
When
you try to compile, you will get the compile time error
MyThread.java:5: error: unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(1000); ^ 1 error
To
make the above program run, handle the exception
class MyThread implements Runnable{ public void run(){ System.out.println("About to call sleep method"); try{ Thread.sleep(1000); } catch(InterruptedException e){ } System.out.println("sleep time finished"); } public static void main(String args[]){ MyThread task = new MyThread(); Thread t1 = new Thread(task); t1.start(); } }
Output
About to call sleep method sleep time finished
No comments:
Post a Comment