Wednesday, 3 July 2019

Prevent a Thread : yield()

  • yield() method causes "to pause current executing Thread for giving the chance of remaining waiting Threads of same priority".
  • If all waiting Threads have the low priority or if there is no waiting Threads then the same Thread will be continued its execution.
  • If several waiting Threads with same priority available then we can't expect exact which Thread will get chance for execution.
  • The Thread which is yielded when it get chance once again for execution is depends on mercy of the Thread scheduler.
  • public static native void yield();
 Lifecycle Diagram: Below is the life cycle diagram of a Thread using yield()


class MyThread extends Thread
{
      public void run()
      {
                  for(int i=0;i<5;i++)
                  {
                              Thread.yield();
System.out.println("child thread");
                  }
      }
}
class ThreadYieldDemo
{
      public static void main(String[] args)
      {
                  MyThread t=new MyThread(); t.start();
                  for(int i=0;i<5;i++)
                  {
                              System.out.println("main thread");
                  }
      }
}

Output: 
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
  • In the above program child Thread always calling yield() method and hence main Thread will get the chance more number of times for execution.
  • Hence the chance of completing the main Thread first is high.
Note : Some operating systems may not provide proper support for yield() method.


Thanks..!!

No comments:

Post a Comment