Reputation: 23
Code:
class A extends Thread {
public void run() {
Thread.yield();
System.out.println("Child Thread");
}
}
public class Human {
public static void main (String agrs[]) {
A t1 = new A();
A t2 = new A();
A t3= new A();
A t4= new A();
A t5= new A();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
for(int a=0;a<1000;a++) {
System.out.println(a);
}
}
}
Output:
626
627
628
629
630
a's value
a's value
a's value
631
When I run my program the output is varied from run to run. Even when I use the yield()
method to let the main thread first finish it's job. But still now I get mixed outputs. Why?
Upvotes: 0
Views: 1682
Reputation: 4763
This is an add-on to Dakkaron's good advice.
What is it that you are trying to achieve? Are you just trying to learn about threads?
As Dakkaron explained Thread.yield()
will not provide any guaranteed behaviour. If you are just wanting to learn about suspending threads and see if you can get the main thread to finish its work before the other threads complete then you could use Thread.sleep(1)
. You would only really want to use this is a test scenario though - not in your production code since it obviously impacts performance. If you are trying to exert some control over the sequence of threads then you could consider threading priorities but this mechanism is only really to be used for trying to improve performance, not to exert execution control.
If you are learning how to write multithreaded code then you are encouraged not to work with threads directly but to learn about better abstractions that are provided as part of the Executor framework (the link is to version 8 but the framework has been around since the Tiger release 1.5).
Upvotes: 2
Reputation: 3881
You need to set priority on threads. Thread.yield() causes the currently executing thread object to temporarily pause and allow other high priority threads to execute. Remember don't rely on thread priorities when designing your multithreaded application.Because thread-scheduling priority behaviour is not guaranteed, use thread priorities as a way to improve the efficiency of your program, but just be sure your program doesn't depend on that behaviour for correctness.
Upvotes: 1
Reputation: 6276
Thread.yield()
is not what you need here. What that function does is it tells the VM that this thread is willing to give up the CPU for now. Neither does it specify for how long, nor does it force the VM to give the CPU allocation to another thread. The exact behaviour of this function is not standardised. That means, the VM isn't even required to do anything at all!
All this function does is to signal that now would be a good time to hand the CPU to another thread.
What you need is a mutex, a semaphore or synchronized
, so basically any kind of real synchronisation.
I'd recommend you to go through some tutorials on multithreading.
Upvotes: 2