Friday, 26 August 2016

Yield Method Implementation

Static Thread.yield() method implementation

This function is use to make current thread back to runnable state and to allow other threads of the same priority to execute .
Actually there is no guarantee that the yielding thread won’t just be chosen again all over the others

Example :-
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package multithreadingtc;

/**
 *
 * @author shashank
 */

class Multithreading implements Runnable
{
     public void run()
    {
        for(int i=1;i<=100;i++)
        {
            System.out.println("run by" + Thread.currentThread().getName() + " remainder is i is " +i%10);
          
               Thread.yield();
           
        }
    }
}
public class MultithreadingTC{

    public static void main(String[] args) {
        // TODO code application logic here
        Multithreading th = new Multithreading();
        Thread t = new Thread(th);
        t.setName(" first");
        t.setPriority(4);
        t.start();
        Thread t2 = new Thread(th);
        t2.setPriority(4);
        t2.setName(" third");
        t2.start();
        Thread t1 = new Thread(th);
        t1.setName(" second");
        t1.setPriority(4);
        t1.start();
      
    }
   

}

No comments:

Post a Comment