Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to know when thread is waiting?

Is there any neat solution of knowing when a thread has been put into wait status? I am putting threads to wait and I notify them when i need it. But sometimes I want to know if a thread is currently waiting, and if so, I have to do something else.

I could probably set a flag myself to true/false. But I can't imagine there is a better way to do this?

like image 375
Stefan Hendriks Avatar asked Dec 01 '09 11:12

Stefan Hendriks


People also ask

What are wait () notify () notifyAll ()?

The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor. A thread waits on an object's monitor by calling one of the wait() method.

Is wait () in thread class?

wait() causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0). The current thread must own this object's monitor.

What happens when a thread is waiting?

A thread is in the waiting state when it wants to wait on a signal from another thread before proceeding. Once this signal is received, it becomes runnable. A thread moves to the blocked state when it wants to access an object that is being used (locked) by another thread.

What happens when notify () is called and no thread is waiting?

In other words, if the notify() method is called when no other thread is waiting, notify() simply returns and the notification is lost. A thread that later executes the wait() method has to wait for another notification to occur.


2 Answers

The method getState() of a thread returns a Thread.State which can be:

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED

See Thread.State.

like image 156
Alexander Egger Avatar answered Oct 01 '22 23:10

Alexander Egger


Have you looked at Thread.getState?

like image 30
Konamiman Avatar answered Oct 02 '22 00:10

Konamiman