Java Reference
In-Depth Information
just put the money it owes you into your everyday account, making your financial footwork
unnecessary and thus removing your need to continue. If your thread had not yielded, it
might not have received the money until after it was done with all six bank operations. If your
thread is performing a prolonged or expensive operation, it's a good idea to yield occasionally.
Caution You should not rely on thread priorities, and by extension yielding, to resolve your threading
issues. Implementation of thread scheduling, including yielding, is completely up to the JVM manufacturer.
So it is possible that different operating systems, or even two different JVMs on one operating system, may
deal with yielding differently. So go ahead and yield in your programs, but never count on the yielding to
actually occur.
Blocking
Blocking is the act of pausing execution until a lock becomes available. If your thread is
attempting to obtain a lock some other thread already owns, then it will block until the other
thread releases its lock. This simply means that the thread goes into a state of hibernation
until the event comes to pass. In this case, the lock becoming available is the event.
What does this mean for other threads? It means that they are free to use the CPU cycles
that the blocking thread has a right to but is not using. However, the blocking thread keeps
exclusive control over any other resources it had explicitly locked. Also, other threads should
be prepared for the blocking thread to start again at any point, because the event that will trig-
ger it could happen at any time.
Note The JVM handles changing threads from the Thread.State.BLOCKED state to the Thread.
State.RUNNABLE state for you. You do not have to do anything special in your code to tell any other
threads that you are about to release a lock on an object.
Sleeping
Sleeping is the act of waiting for at least a specified amount of time. Imagine that you are using
the ATM, but get a message on screen telling you that the system is congested. You might
decide that you want to give up for 5 minutes and then wander over to try to use it again after
that time has passed. This act frees up the ATM for at least the next 5 minutes. After that time
period expires, you walk over to the ATM and join the line waiting for its use.
Note A sleeping thread is guaranteed to wait at least as long as specified. However, it might wait longer,
depending on the whims of the thread scheduler.
Search WWH ::




Custom Search