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(); thread.start(); 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中的重要性是什么?的详细内容。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)