Monday, September 8, 2014

Thread Life Cycle

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.Thread goes from running to runnable state after yield() is called and from there it again picked up by scheduler.
  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() causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).Thread goes from running to sleep state after sleep() is called and from sleep state to runnable after sleep time is over.