Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Have I got something wrong? Can anybody explain this behaviour to me? Any help would be appreciated!

like image 828
Chris Avatar asked Mar 28 '10 19:03

Chris


People also ask

Is Wait a blocking function?

Wait is the action performed by a thread when blocked. Often with concurrency primitives, the function call itself may have the name wait() or await(), signaling that the thread will block until a condition is met.

What happens when a thread is blocked in Java?

The running thread will block when it must wait for some event to occur (response to an IPC request, wait on a mutex, etc.). The blocked thread is removed from the running array, and the highest-priority ready thread that's at the head of its priority's queue is then allowed to run.

Is wait () in thread class?

wait() method is a part of java. lang. Object class. When wait() method is called, the calling thread stops its execution until notify() or notifyAll() method is invoked by some other Thread.


1 Answers

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.

like image 90
Josef Grahn Avatar answered Sep 18 '22 18:09

Josef Grahn