Whether Thread.yield() gives guarantee that Thread will keep waiting until execution of other Thread ?
-
3what is your question? – SpringLearner Apr 21 '15 at 13:10
-
This is answered by the documentation: [`Thread#yield()`](http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#yield--) – Radiodef Apr 21 '15 at 13:15
-
@SpringLearner, I agree it's a very weakly stated question, but I don't think he was asking whether `Thread.yield()` means the same as `Thread.sleep(0)`. The question that I asnwered was, "why does Thread.yield() exist? and when am I supposed to call it?" And it looks like my answer is what the OP wanted to hear. – Solomon Slow Apr 21 '15 at 14:37
1 Answers
Thread.yield()
is a relic from thirty or so years ago when threads were implemented on single-CPU computers with no support from the operating system, by a technique called "cooperative multitasking".
Back in those days, the only way a thread ever got to run is when some other thread "yielded" the CPU by calling some function in the thread library. Usually this would happen at points where one thread needed to wait for something, and so naturally, that was a good time to let other threads run.
The yield() call was for the special case where a thread was doing a long computation, and it didn't want to wait for anything. The programmer would sprinkle a few yield() calls at strategic places in the algorithm to make sure that other threads could respond to events in a timely fashion.
Let me say that again, because it's important: A thread would call yield() at points where it did not want to wait.
Some form of yield() has survived in just about every threading library since, but it no longer serves any purpose unless you are re-implementing the lowest-level synchronization primitives as a learning exercise.

- 25,130
- 5
- 37
- 57