Java Thread: sleep() and interrupt() methods

sleep()

Thread.sleep() method will  hold the execution of the currently running thread for a defined period of time. once the sleeping time os over, it will resume the execution. sleep() method is a static method available in java thread class. unlike wait() method, sleep method will not release any object monitor before going to sleep. it is guaranteed to sleep the thread for a given time period unless some other thread interrupt it (by calling interrupt() method on the thread object).

 

The execution of the above program will produce the following output.

main thread is started
main thread will be slept for 5 seconds
main thread resumed after sleeping
main thread completed

 

As you can see that the main thread is started and sleeping for 5 seconds. The  application(main thread) will sleep for 5 seconds and wake up after sleeping duration over.

 

Interrupting the sleeping thread with interrupt()

The interrupt() method can be called on a sleeping thread object to interrupt its sleep and move back to the runnable state.  The below example will demonstrate how the interrupt() is really working.

The main thread creates and starts two thread objects known as threadA and threadBthreadA will be slept for 15 seconds while threadB is slept for 5 seconds. Therefore the threadB is guaranteed to be wake up before threadA wakes up.  Once the threadB wakes up, it interrupts the threadA which is still sleeping. Then the sleeping threadA will get interrupted and  it throws the InterruptedException. The thrown exception will be caught by the catch block and the threadA will be resumed from the catch block.

If you run the above sample program, you will get the following output.

main thread is started
main thread completed
ThreadB is running
ThreadB is sleeping for 5 seconds
ThreadA is running
ThreadA is sleeping for 15 seconds 
ThreadB wakes up from sleep and interrupts ThreadA 
ThreadB completed
Sleep of ThreadA get interrupted 
ThreadA completed

One thought on “Java Thread: sleep() and interrupt() methods

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s