
yield()方法是Thread类的静态方法,它可以停止当前正在执行的线程线程,并将给相同优先级的其他等待线程一个机会。 如果没有等待线程或者所有等待线程都低优先级,则同一个线程将继续执行。 yield()方法的优点是有机会执行其他等待线程,因此如果我们当前线程需要更多时间来执行并将处理器分配给其他线程。
public static void yield()
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());
}
}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
以上就是yield()方法在Java中的重要性是什么?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号