What is yield() method?

It is a static method of class Thread.
It’s job is to make the currently running thread head back to runnable to allow other threads of
the same priority to get their turn. So the intention is to use yield() to promote
graceful turn-taking among equal-priority threads.
A yield() won't ever cause a thread to go to the waiting/sleeping/ blocking
state. At most, a yield() will cause a thread to go from running to runnable, but
again, it might have no effect at all.
Example:
class demo1 implements Runnable
{
public void run(){
System.out.println(Thread.currentThread());
Thread.yield();
System.out.println(Thread.currentThread());
}
};
class demo
{
public static void main(String[] args){
demo1 d1=new demo1();
demo1 d2=new demo1();
Thread t1=new Thread(d1,"first");
Thread t2=new Thread(d2,"second");
t1.start();
t2.start();
}};
Output:
Thread[first,5,main]
Thread[second,5,main
Thread[first,5,main]
Thread[second,5,main]
Press any key to continue . . .
Here t1 starts running. When yield() is called t1 goes to runnable state and t2 starts running.
Then t2 also faces the yield() and goes to runnable state and t1 runs again. Again it goes to runnable and allow t2 to run.
The whole case changes if the thread priority is different.

1 comment:

  1. I really like your ideas. I truly appreciate your effort in publishing this article. Keep it up and God bless.

    Jax
    www.imarksweb.org

    ReplyDelete