yield()方法在java中的重要性是什么?-kb88凯时官网登录

时间:2023-09-07
阅读:

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中的重要性是什么?的详细内容。

返回顶部
顶部
网站地图