NaveenBharadwaj
NaveenBharadwaj

Reputation: 1333

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. 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] 

Upvotes: 0

Views: 1400

Answers (3)

TheLostMind
TheLostMind

Reputation: 36304

As with almost all aspects of Multithreading, even your case isn't guaranteed to behave as expected. Thread.yield() is just like a suggestion to the OS telling - if it is possible, then please execute other threads before this one. 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 :

   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)

Upvotes: 2

user3717646
user3717646

Reputation: 436

Read This article. yield method is to request for a thread to sleep. it may be happen or not.

Upvotes: 0

codingenious
codingenious

Reputation: 8653

The java.lang.Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute.

NOTE : That other thread can be same thread again. There is no guarantee which thread be chosen by JVM.

Upvotes: 5

Related Questions