Difference between yield(), join(), sleep() method?

Difference between yield(), join(), sleep() method?

Difference between yield(), join(), sleep() method?

Difference between yield(), join(), sleep() method?
We can prevent thread execution by using the following method.
  1. yield()
  2. join()
  3. sleep()

public static native void yield() 

  • yield() method causes to pause current executing thread to give the chance for waiting threads of the same priority.
  • If there is no waiting thread or all waiting threads have low priority then the same thread can continue its execution.
  • If multiple threads are waiting with same priority then which waiting thread will get chance we can expect it depends on thread scheduler.
  • The thread which is yielded, when it will get the chance once again it depends on thread scheduler and we can’t expect exactly.
  • 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.
public class MyThread extends Thread {

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Child Thread");
            Thread.yield(); // line 1
        }
    }
}
public class Testing { 
 public static void main(String[] args) { 
  MyThread mt = new MyThread();
  mt.start();
  for (int i = 0; i < 10; i++) 
   { 
     System.out.println("Main Thread");
   } 
  } }
  • In the above program if we are commenting line 1 then both thread will be executed simultaneously and we can expect which thread will complete first.
  • If we are not commenting line 1 then child thread always calls yield() method because of the main thread will get chance more no of times and the chance of completing main thread first is high.
  • Note:- Some platforms won’t provide proper support for yield() method.

Leave a Reply

Your email address will not be published. Required fields are marked *

*