Wednesday, February 27, 2013

Sleep, Yield, and Join


We can prevent a thread from execution by using any of the 3 methods of Thread class:
  1. yield()
  2. join()
  3. sleep()
  1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
  2. join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter into waiting state until t2 completes its execution.
  3. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).

    Sleeping is used to delay execution for a period of time, and no locks are released when a thread goes to sleep.
    A sleeping thread is guaranteed to sleep for at least the time specified in the argument to the sleep() method (unless it's interrupted), but there is no guarantee as to when the newly awakened thread will actually return to running.
    The sleep() method is a static method that sleeps the currently executing thread's state. One thread cannot tell another thread to sleep.
    The setPriority() method is used on Thread objects to give threads a priority of between 1 (low) and 10 (high), although priorities are not guaranteed, and not all JVMs recognize 10 distinct priority levels—some levels may be treated as effectively equal.
    If not explicitly set, a thread's priority will have the same priority as the priority of the thread that created it.
    The yield() method may cause a running thread to back out if there are runnable threads of the same priority. There is no guarantee that this will happen, and there is no guarantee that when the thread backs out there will be a different thread selected to run. A thread might yield and then immediately reenter the running state.
    The closest thing to a guarantee is that at any given time, when a thread is running it will usually not have a lower priority than any thread in therunnable state. If a low-priority thread is running when a high-priority thread enters runnable, the JVM will usually preempt the running low-priority thread and put the high-priority thread in.
    When one thread calls the join() method of another thread, the currently running thread will wait until the thread it joins with has completed.

No comments:

Post a Comment