Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How to Implement thread.yield() in Java: Examples

Last updated on Jul 21,2020 5.1K Views


Theoretically, to ‘yield’ means to let go, to give up, to surrender. A yielding thread tells the virtual machine that it’s willing to let other threads be scheduled in its place. This indicates that it’s not doing something too critical. Note that it’s only a hint, though, and not guaranteed to have any effect at all. In this thread.yield() in Java, we will cover the following topics:

 

Introduction to thread.yield() in Java

yield() is defined as following in Thread.java. A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilize a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.

Syntax:

public static native void yield();

 

Difference between wait, sleep, join and yield in Java


 
yield() vs wait()

  • While yield() is invoked in the context of the current thread, wait() can only be invoked on an explicitly acquired lock inside a synchronized block or method
  • Unlike yield(), it is possible for wait() to specify a minimum time period to wait before any attempt to schedule the thread again
  • With wait() it is also possible to wake the thread anytime through an invocation of notify() or notifyAll() on the concerned lock object

 yield() vs sleep()

  • While yield() can only make a heuristic attempt to suspend the execution of the current thread with no guarantee of when will it be scheduled back, sleep() can force the scheduler to suspend the execution of the current thread for at least the mentioned time period as its parameter.

 yield() vs join()

  • The current thread can invoke join() on any other thread which makes the current thread wait for the other thread to die before proceeding
  • Optionally it can mention a time period as its parameter which indicates the maximum time for which the current thread should wait before resuming

 

Example of thread.yield() in Java

public class JavaYieldExp extends Thread  
{  
public void run()  
{  
        for (int i=0; i<3 ; i++)  
            System.out.println(Thread.currentThread().getName() + " in control");  
    }  
    public static void main(String[]args)  
    {  
        JavaYieldExp t1 = new JavaYieldExp();  
        JavaYieldExp t2 = new JavaYieldExp();  
        // this will call run() method  
        t1.start();  
        t2.start();  
        for (int i=0; i<3; i++)  
        {  
            // Control passes to child thread  
            t1.yield();  
            System.out.println(Thread.currentThread().getName() + " in control");  
        }  
    }  
}  

Output:

thread.yield() in Java

 

The next example shows the usage of java.lang.Thread.yield() method:

import java.lang.*;
public class ThreadDemo implements Runnable {
   Thread t;
   ThreadDemo(String str) {
      t = new Thread(this, str);
      // this will call run() function
      t.start();
   }
   public void run() {
      for (int i = 0; i < 5; i++) {
         // yields control to another thread every 5 iterations
         if ((i % 5) == 0) {
            System.out.println(Thread.currentThread().getName() + "
            yielding control...");
            /* causes the currently executing thread object to temporarily 
            pause and allow other threads to execute */
            Thread.yield();
         }
      }
      System.out.println(Thread.currentThread().getName() + " has finished executing.");
   }
   public static void main(String[] args) {
      new ThreadDemo("Thread 1");
      new ThreadDemo("Thread 2");
      new ThreadDemo("Thread 3");
   }
}

Output:

With this, we have come to the end of our article. I hope you understood how the thread.yield() in Java works and how it is used the programming language.

Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Thread.yield() in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Implement thread.yield() in Java: Examples

edureka.co