May 31, 2011

Java threads yield() method

The yield() method is a static method on the Thread class that causes the currently executing thread to go to the runnable state, yielding to a higher priority thread to become the current executing thread. Whether execution of the yield() method will produce the desired result is the prerogative of the Thread Scheduler.


package info.icontraining.threads;

public class MyRunnable implements Runnable {
 
   public static void main(String[] args) {
      Thread t = new Thread(new MyRunnable());
      t.start();
  
      for(int i=0; i<50; i++) {
         System.out.println("Inside main");
      }
   }
 
   public void run() {
      for(int i=0; i<50; i++) {
         System.out.println("Inside run");
         Thread.yield();
      }
   }
}

No comments:

Post a Comment