Thread.yield()
, it goes back to the Runnable state, so that the thread scheduler can decide which thread to run next.
yield()
method in the Thread
class:
public static native void yield()
Thread.yield()
.
class MyThread extends Thread
{
@Override
public void run()
{
// Child thread prints numbers from 1 to 5
for (int i = 1; i <= 5; i++)
{
System.out.println(getName() + " is running: " + i);
}
}
}
public class YieldDemo
{
public static void main(String[] args)
{
System.out.println("Main thread started execution.");
// Main thread creates another thread (child thread)
MyThread t1 = new MyThread();
t1.setName("Child-Thread");
t1.start();
// Yielding once in the main method
// π Here the MAIN THREAD gives a chance (hint) to other threads of equal priority (Child-Thread)
// If scheduler accepts the hint, Child-Thread will run first.
Thread.yield();
// Main thread continues its execution (printing 1 to 5)
for (int i = 1; i <= 5; i++)
{
System.out.println("Main thread is running: " + i);
}
System.out.println("Main thread finished execution.");
}
}
Main thread started execution. Child-Thread is running: 1 Child-Thread is running: 2 Child-Thread is running: 3 Child-Thread is running: 4 Child-Thread is running: 5 Main thread is running: 1 Main thread is running: 2 Main thread is running: 3 Main thread is running: 4 Main thread is running: 5 Main thread finished execution.
Main thread started execution. Main thread is running: 1 Main thread is running: 2 Main thread is running: 3 Main thread is running: 4 Main thread is running: 5 Main thread finished execution. Child-Thread is running: 1 Child-Thread is running: 2 Child-Thread is running: 3 Child-Thread is running: 4 Child-Thread is running: 5
Note: The yield()
method is just a hint to the thread scheduler.
It does not guarantee that the current thread will pause immediately or that another thread will run next.
Behavior depends on the JVM and operating system.
yield()
is a static method of the Thread
class.yield()
is only a hint to the thread scheduler; it is not guaranteed that the current thread will stop executing.yield()
.yield()
is declared as native, meaning its actual implementation is provided in another language (like C/C++) inside the JVM.yield()
is platform-dependent and may vary across operating systems and JVM implementations.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.