Java/multithreading

Advertisement


Question
hello sir!
My doubt is on yield method in multi threading.
Yield method is used to put a currently executing thread in pause and so other threads can run.
but it is not happening.i am expressing my doubts using below programme.please read and tell me how to

understand yield method.
------------------------------------------------------------------
class thread3
{
public static void main(String args[])
{
Thread count1=new Thread(new CountDownEven());
Thread count2=new Thread(new CountDownOdd());
count1.start();
count2.start();
Thread t=Thread.currentThread();
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();
}
}
}
out put:
main----11
Thread-1----1
Thread-0----0
Thread-1----3
main----13
Thread-1----5
Thread-0----2
Thread-1----7
main----15
Thread-1----9
Thread-0----4
main----17
Thread-0----6
main----19
Thread-0----8
------------------------------------------------------------------
my doubts:
1)see the first four lines of out put.before coming to main thread, thread1 is getting executed twice.
see the out put between 5 to 8 lines. before coming to main thread, thread1 is getting executed twice
see the out put between 9 to 11 lines. thread one is getting executed only once before coming to main thread.
2)why thread1 executed twice before,and once now?
3) how can i understand yield method?

Answer
Thread.yield() doesn't guarantee anything. It could let other threads on the system run that aren't part of the running program. The only use of yield() is to prevent using too many system resources at once. If you want threads to wait for other threads you will have to use a different methods like sleep and notify.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.