Java Thread wait() => blocked?
According to Java thread state info calling wait() will result a thread to go in BLOCKED state. However this piece of code will result (after being called) in a Thread in WAITING State.
class bThread extends Thread {
public synchronized void run() {
try {
wait();
} catch (In开发者_如何学PythonterruptedException e) {
e.printStackTrace();
}
}
}
Have I got something wrong? Can anybody explain this behaviour to me? Any help would be appreciated!
The thread is WAITING until it is notified. Then it becomes BLOCKED trying to reenter the synchronized region until all other threads have left.
Relevant parts from the link you posted (about WAITING):
For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object.
and (about BLOCKED):
A thread in the blocked state is waiting for a monitor lock to [...] reenter a synchronized block/method after calling Object.wait.
The last part occurs when the thread tries to return from wait(), but not until then.
The monitor executes one thread at a time. Assuming you have T1-T10 threads, 9 are BLOCKED
and one is RUNNABLE
. Every once in a while, the monitor picks a new thread to run. When that happens, the chosen/current thread, say T1, goes from RUNNABLE
to BLOCKED
. Then another thread, say, T2, goes from BLOCKED
to RUNNABLE
, becoming the current thread.
When one of the threads needs some information to be made available by another thread, you use wait()
. In that case, the thread will be flagged as WAITING
until it is notify()
ed. So, a thread that is waiting will not be executed by the monitor until then. An example would be, wait until there are boxes to be unloaded. The guy loading boxes will notify me when that happens.
In other words, both BLOCKED
and WAITING
are status of inactive threads, but a WAITING
thread cannot be RUNNABLE
without going to BLOCKED
first. WAITING
threads "don't want" to become active, whereas BLOCKED
threads "want" to, but can't, because it isn't their turn.
I think.
Where did you see it say stuff like that?
In the same page you linked, thread.state, it clearly states that
WAITING will be after Object.wait()
BLOCKED will be before entering synchronized
Waiting is when it's not doing anything at all. Blocked is when it's trying to start running again but hasn't been allowed to yet.
There is some confusing terminology going on here. When a thread calls wait on an object it goes into the WAIT state. When threads are waiting to grab a lock, they belong to the wait set for that lock, but they are in the BLOCKED state.
Confusing but somehow it makes sense!
Just as a reminder, you should always call wait() inside a while loop waiting on the condition for entering the synchronized region/critical section. This is because Java has "spurious wakeups" (essentially, a thread can wakeup at any moment for no reason).
精彩评论