Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Yield Method

The yield() method is used by the running thread to provide a chance to other waiting threads of same priority for their execution.
If two or more waiting threads have the same priority, then thread scheduler decides their execution sequence.
If waiting threads have low priority than running thread, they do not get the chance to execute until the running thread completes its work.

Syntax of yield() method

public static native void yield()

Example

class ChildThread extends Thread
{
    public void run()
    {
        for(int i=1;i<=10;i++)
        {
            System.out.println("Child Thread Running");
        }
    }
}

class YieldDemo
{
    public static void main(String args[])
    {
        ChildThread c = new ChildThread();
        c.start();
        for(int i=1;i<=10;i++)
        {
            System.out.println("Main Thread Running");
            Thread.yield();
        }
    }
}

Output

Main Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Child Thread Running
Main Thread Running
Main Thread Running
Main Thread Running
Main Thread Running
Main Thread Running
Main Thread Running
Main Thread Running
Main Thread Running
Main Thread Running

In the above program, main thread and Child thread have the same priority. Therefore by calling yield() method on the main thread, main thread gives most of the chance to child thread to execute. Hence Child thread gets execute earlier than the main thread.

 

Leave a reply