Javatpoint Logo

What is sleep() and yield()Concepts in Java?

By: rajmsc*** On: Mon Mar 17 12:00:40 IST 2014     Question Reputation5 Answer Reputation0 Quiz Belt Series Points2  7Blank User
Hi

Can any one explain to me what is sleep() and yield()Concepts in Java?


Thanks in a Advance


Regards
Raj Kumar R
Up2Down

 
If we want a thread to relinqunish control to another thread to equal priority before its run comes,we can do so by using yield() method it is ussed in Runnable state of thread.
we can put a thread to slep for a specified time peroid using the sleep(time) where time is milliseconds.this means that the period is out of the queue during the method time peroid.The thread re-enters the runnable state as soon as this time period is elapsed.
Image Created0Down

By: [email protected] On: Tue Mar 18 10:54:26 IST 2014 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :10Yes1No
 
Thread.sleep()

The current thread changes state from Running to Waiting/Blocked as shown in the diagram below.
Any other thread with reference to the thread currently sleeping (say t) can interrupt it calling t.interrupt()
the call to sleep has to be encapsulated to catch the checked exception of InterruptedException
After the time period for which the thread was set to sleep it goes to the Runnable state and might not run immediately! It has to wait for the Thread Scheduler to schedule it for its time slice.

Thread.yield()

Calling it may cause the Thread Scheduler to move the current thread from Running to Runnable state and execute another same priority thread which was in Runnable state. This transition of state takes place only if there is some other thread of same priority in Runnable state. Hence the no guarantee that the thread will stop execution as the criteria of another same priority thread might not be met.
.yield() is much based on the Thread Priorities concept. (All thread are assigned priorities and when a thread of higher priority is in Runnable state it ususally preempts / stops execution of lower priority threads depending on implementation of ThreadScheduler.)
Image Created0Down

By: [email protected] On: Wed Mar 19 12:00:01 IST 2014 Question Reputation0 Answer Reputation359 Belt Series Points0 359User Image
Are You Satisfied :13Yes1No