简体   繁体   English

yield()方法未按预期工作

[英]yield() method not working as expected

public class YieldDemo extends Thread{

   public static void main(String[] args) {
        YieldDemo y1 = new YieldDemo();
        YieldDemo y2= new YieldDemo();

        y1.start();
        y2.start();
   }

   public void run() {
      for(int i=0;i<=5;i++) {
           if(i==3) {
               Thread.yield();
           } else
               System.out.println(i+Thread.currentThread().toString());
           }
   }
}

As per the documentation of yield(), thread-1 should yield and allow thread-2 to process after 3rd loop. 根据yield()的文档,线程1应该屈服并允许线程2在第3个循环之后进行处理。 However, the output is not as expected. 但是,输出不符合预期。 Same thread continues skipping 3rd iteration. 同一线程继续跳过第三次迭代。 After one thread completes the loop, other thread executes with same behaviour. 一个线程完成循环后,其他线程以相同的行为执行。 Please explain. 请解释。

Output: 输出:

0Thread[Thread-1,5,main] 
1Thread[Thread-1,5,main] 
2Thread[Thread-1,5,main] 
4Thread[Thread-1,5,main] 
5Thread[Thread-1,5,main] 
0Thread[Thread-0,5,main] 
1Thread[Thread-0,5,main] 
2Thread[Thread-0,5,main] 
4Thread[Thread-0,5,main] 
5Thread[Thread-0,5,main] 

The java.lang.Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute. java.lang.Thread.yield()方法使当前正在执行的线程对象暂时暂停并允许其他线程执行。

NOTE : That other thread can be same thread again. 注意 :该其他线程可以再次成为同一线程。 There is no guarantee which thread be chosen by JVM. 不能保证JVM选择哪个线程。

As with almost all aspects of Multithreading , even your case isn't guaranteed to behave as expected. Multithreading的几乎所有方面一样,即使您的情况也不能保证表现出预期的效果。 Thread.yield() is just like a suggestion to the OS telling - if it is possible, then please execute other threads before this one . Thread.yield()就像对操作系统的建议一样- 如果可能的话,请在执行此操作之前执行其他线程 Depending on the architecture of your system (number of cores, and other aspects like affinity etc etc) the OS might just ignore your request. 根据系统的体系结构(内核数,以及诸如亲缘关系等其他方面),操作系统可能只是忽略您的请求。

Also, after JDK6U23, the JVM might just change your code to : 另外,在JDK6U23之后,JVM可能只是将您的代码更改为:

   public void run() {
      for(int i=0;i<=5;i++) {
   // 3 is too darn small. and yield() is not necessary
   // so let me just iterate 6 times now to improve performance.  
     System.out.println(i+Thread.currentThread().toString());

   }

yield() can totally be ignored (which might be happening in your case. If you are getting the same result over and over again) yield()可以完全忽略(在您的情况下可能会发生。如果您一次又一次地得到相同的结果)

Read This article. 阅读文章。 yield method is to request for a thread to sleep. yield方法是请求线程休眠。 it may be happen or not. 它可能发生与否。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM