Java/yield in java

Advertisement


Question
Hi sir!yield method makes currently executing thread to pause to make another active thread to run.
i got some doubts on yield method.i previously asked about yield.but this time some what differnent than previous.I am asking based on below code.
I hope you help me.
------------------------------------------------------------------
class thread7
{
public static void main(String args[])
{
Thread count1=new Thread(new CountDownEven());
Thread count2=new Thread(new CountDownOdd());

Thread t=Thread.currentThread();
count1.start();
count2.start();
for(int i=11;i<=20;i=i+2)
{
System.out.println(t.getName()+"----"+i);
Thread.yield();
}

}
}
class CountDownEven implements Runnable
{
public void run()
{
Thread t=Thread.currentThread();
for(int i=0;i<10;i=i+2)
{
System.out.println(t.getName()+"----"+i);
Thread.yield();
}
}
}
class CountDownOdd implements Runnable
{
public void run()
{
Thread t=Thread.currentThread();
for(int i=1;i<10;i=i+2)
{
System.out.println(t.getName()+"----"+i);
Thread.yield();
}
}
}
------------------------------------------------------------------
Mydoubts:
1)Does yield method guarantees that after executing yield control goes to another active thread?
see in the below output in line 3,4 thread 0 got executed two times.why this happened?Is it due to drawback of yield or due to cpu execution?
2)what are the drawbacks of yield method?
3)If it has drawbacks then why yield method?what is the purpose of yield?
------------------------------------------------------------------
output:
-------------
Thread-0----0
main----11
Thread-0----2
Thread-0----4
Thread-1----1
main----13
Thread-1----3
Thread-0----6
Thread-1----5
main----15
Thread-1----7
Thread-0----8
Thread-1----9
main----17
main----19
------------------------------------------------------------------

Answer
Hello,

Using yield() to know when to give up execution won't work as like I told you previously , yield is not generic in all platforms. Only the scheduler determines which one if they are all on low priority but if one is on high priority, it will continue to execute until something happens to it. what might happen depends on other activities the CPU has to do which has higher priority than the execution of that thread.  

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


henry joe

Expertise

I can confidently answer questions relating to JSE and JEE6 . Please no questions on JME.

Experience

I am experienced in JSE and JEE6

Education/Credentials
I am a BSEng graduate

©2016 About.com. All rights reserved.