Some questions regarding the Thread.yield() method. What I have understood is When we call,Thread.Yield(), the currently running thread will go back to the runnable state.So dependes on the thread priority thread scheduler will execute next higher priority thread. Now I have one sample program. Please see below.
package thread;
public class YieldTest implements Runnable {
@Override
public synchronized void run() {
System.out.println(Thread.currentThread().getName()+", executing..");
for(int i = 0 ; i <5;i++){
if(i==2){
Thread.yield();
System.out.println(Thread.currentThread().getName()+": "+i+" yielded()");
/*try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+": "+i+" yielded()");
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}else{
System.out.println(Thread.currentThread().getName()+": "+i);
}
}
}
public static void main(String[] args) {
YieldTest test = new YieldTest();
Thread t1 = new Thread(test);
t1.setName("A");
t1.setPriority(9);
Thread t2 = new Thread(test);
t2.setName("B");
Thread t3 = new Thread(test);
t3.setName("C");
t2.setPriority(6);
t2.setPriority(4);
t1.start();
t2.start();
t3.start();
}
}
Here I am getting the output always in the following way,
A, executing..
A: 0
A: 1
A: 2 yielded()
A: 3
A: 4
C, executing..
C: 0
C: 1
C: 2 yielded()
C: 3
C: 4
B, executing..
B: 0
B: 1
B: 2 yielded()
B: 3
B: 4
Now the question is yield() method should go back to the runable state and other thread should execute. so the output should be something like the following way
A, executing..
A: 0
A: 1
A: 2 yielded()
C, executing..
C: 0
C: 1
C: 2 yielded()
A: 3
A: 4
B, executing..
B: 0
B: 1
B: 2 yielded()
C: 3
C: 4
B: 3
B: 4
Also, what about the thread priority. Is it not guaranteed why do we need thread priority?Please correct me If I am wrong.
All your run methods are synchronized on the same object (test). So yielding doesnt acheive anything, since until the first thread’s run method exits, no others can enter their run() methods.
Basically thread 1 starts, and enters the run() method. This is synchronized on ‘this’. After outputting 2 numbers, it yields. But threads 2 and 3 are both waiting to enter the run method, since they cannot obtain a monitor on test. So yield doesnt do anything. The same issue then happens once thread one has finished.