Saturday 1 March 2014

Giving Up the Processor : yield()

Generally higher priority threads get more processor time than low priority threads.

When a low priority thread is running, and a high priority thread came to the ready queue, then Scheduler swaps the low priority thread from Running state and make the processor available for the high priority thread.
If you have a high priority thread which is doing long running operations, then there is a way in java, to voluntarily Relinquishing the Processor for some time.

Signature
public static void yield()

Causes the currently executing thread object to temporarily pause and allow other threads to execute. This is a static method, so we can call it by using class name.

Example
class ThreadYield implements Runnable{
 public void run(){
  for(int i=0; i< 10; i++){
   System.out.println(Thread.currentThread().getName() +"\t" + i);
  }
 }

 public static void main(String args[]){
  ThreadYield task1 = new ThreadYield();
  ThreadYield task2 = new ThreadYield();

  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task2);

  t1.setName("High Priority Thread");
  t2.setName("Low Priority Thread");

  t1.setPriority(10);
  t2.setPriority(1);

  t1.start();
  t2.start();
 }
}
   
sample Output1
High Priority Thread 0
High Priority Thread 1
High Priority Thread 2
High Priority Thread 3
High Priority Thread 4
High Priority Thread 5
High Priority Thread 6
High Priority Thread 7
High Priority Thread 8
High Priority Thread 9
Low Priority Thread 0
Low Priority Thread 1
Low Priority Thread 2
Low Priority Thread 3
Low Priority Thread 4
Low Priority Thread 5
Low Priority Thread 6
Low Priority Thread 7
Low Priority Thread 8
Low Priority Thread 9

Some points to remember
1. just like sleep(), yield() also doesn't release the lock.

Example
class ThreadYield implements Runnable{
 static Object obj = new Object();

 public void run(){
  synchronized(obj){
   for(int i=0; i< 10; i++){
    System.out.println(Thread.currentThread().getName() +"\t" + i);
    Thread.currentThread().yield();
   }
  }
 }

 public static void main(String args[]){
  ThreadYield task1 = new ThreadYield();
  Thread t1 = new Thread(task1);
  Thread t2 = new Thread(task1);

  t1.setName("Thread 1");
  t2.setName("Thread 2");

  t1.start();
  t2.start();
 }
}
    
Sample Output

Thread 1 0
Thread 1 1
Thread 1 2
Thread 1 3
Thread 1 4
Thread 1 5
Thread 1 6
Thread 1 7
Thread 1 8
Thread 1 9
Thread 2 0
Thread 2 1
Thread 2 2
Thread 2 3
Thread 2 4
Thread 2 5
Thread 2 6
Thread 2 7
Thread 2 8
Thread 2 9

Thread Priority                                                 volaite keyword                                                 Home

No comments:

Post a Comment