In javadoc there is said that yield method
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
And Katherine Sierra and Bert Bates SCJP book says that
yield() is supposed to do is make the currently running thread head back to runnable to allow other threads of the same priority to get their turn.
So what actually method is doing?
Given a multi-threaded application, yield
will cause the currently executing thread to pause execution and be set in a waiting state. The JVM will then begin running another thread that was previously in a waiting state.
I believe the same thread that just yielded could technically be scheduled to start again.
And I have yet to see this in the wild though. So I think it is safe to avoid.
To elaborate:
In a multi-threaded environment threads are scheduled and unscheduled off and on at the JVM's will. So, even if yield is not called in code, your thread can/will automatically yield to other threads when the JVM decides it should. This allows multi-threading to work in an environment with only one processing core.
Calling yield simply tells the JVM to put the current thread in a waiting state even if the JVM wasn't going to.
I shall attempt an illustration:
The following is a very simplified illustration of the execution of 2 threads over time (assume 1 core)-
Thread\Time 1 2 3 4 5 6 7 8 9
Thread 1 ----------- ----- -------
Thread 2 ------- ---------- ------
Whenever you see a '-'
that means a thread is executing. A ' '
means that the thread is waiting. As you can see, only 1 thread can actually run at a time. So, while 1 runs, the other waits. What yield is intended to do is give other threads a chance to run ahead of the currently running thread.
yield()
is generally used when you are waiting on a thread for something to occur but don't want to block the CPC cycles with something like while(condition){ ...}
. The way yield() works differ from platform to platform and depends on the Thread Scheduler and you shouldn't rely on it behaving in a particular way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With