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:mainthread started:thread-0thread started:mainthread started:thread-0thread started:mainthread started:thread-0thread started:mainthread started:thread-0thread started:mainthread started:thread-0thread ended:mainthread ended:thread-0
以上就是yield()方法在java中的重要性是什么?的详细内容。