Home > Java > javaTutorial > body text

What is the importance of yield() method in Java?

WBOY
Release: 2023-09-07 21:05:02
forward
1385 people have browsed it

What is the importance of yield() method in Java?

yield() method is a static method of the Thread class, which can stop the current execution thread and will give other waiting threads of the same priority a chance. If there are no waiting threads or all waiting threads are low priority, the same thread will continue to execute. yield() The advantage of the method is that there is a chance to execute other waiting threads, so if our current thread needs more time to execute and assign the processor to other threads.

Syntax

public static void yield()
Copy after login

Example

class MyThread extends Thread {
   public void run() {
      for (int i = 0; i < 5; ++i) {
         Thread.yield(); // By calling this method, MyThread stop its execution and giving a chance to a main thread
         System.out.println("Thread started:" + Thread.currentThread().getName());
      }
      System.out.println("Thread ended:" + Thread.currentThread().getName());
   }
}
public class YieldMethodTest {
   public static void main(String[] args) {
      MyThread thread = new MyThread();
<strong>      </strong>thread.start();<strong>
</strong>      for (int i = 0; i < 5; ++i) {
         System.out.println("Thread started:" + Thread.currentThread().getName());
      }
      System.out.println("Thread ended:" + Thread.currentThread().getName());
   }
}
Copy after login

Output

Thread started:main
Thread started:Thread-0
Thread started:main
Thread started:Thread-0
Thread started:main
Thread started:Thread-0
Thread started:main
Thread started:Thread-0
Thread started:main
Thread started:Thread-0
Thread ended:main
Thread ended:Thread-0
Copy after login

The above is the detailed content of What is the importance of yield() method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!