Re: Don't really understand Thread.yield()
From: Alexey Dmitriev (alexeydmitriev_at_inbox.ru)
Date: Mon, 13 Oct 2003 12:49:01 +0600
> The SDK Document reads the following for Thread.yield():
> * Causes the currently executing thread object to temporarily pause
> * and allow other threads to execute.
> I don't really understand what this sentence says. What's happening
> if a thead calls yield()? Will the thread be hung up instantly?
> When will the thread continue to excute? What's the difference between
> sleep() and yield()?
If you want to learn more thoroughly about threads I to you strongly
recommend to buy to gain the book "Java Threads, 2nd edition", Scott
Oaks&Henry Wong. O'Reilly has published it.
For example, in it there is an answer to your answer.
What actually happens when a thread yields?
In terms of the state of the thread, nothing happens:
the thread remains in the runnable state. But logically, the thread is
moved to the end of its priority
queue, so the Java virtual machine picks a new thread to be the
currently running thread, using the
same rules it always has. Clearly, there are no threads that are higher
in priority than the thread that
has just yielded, so the new currently running thread is selected among
all the threads that have the
same priority as the thread that has just yielded. If there are no other
threads in that group, the
yield() method has no effect: the yielding thread is immediately
selected again as the currently
running thread. In this respect, calling the yield() method is
equivalent to calling sleep(0).
If there are other threads with the same priority as the yielding
thread, then one of those other threads
becomes the currently running thread. Thus, yielding is an appropriate
technique provided you know
that there are multiple threads of the same priority. However, there is
no guarantee which thread will
be selected: the thread that yields may still be the next one selected
by the scheduler, even if there are
other threads available at the same priority.