Re: blocking calls in java
- From: "Daniel Dyer" <dan@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Fri, 29 Apr 2005 13:52:23 +0100
On Fri, 29 Apr 2005 13:22:16 +0100, Gyro <appcoder@xxxxxxxxxxxx> wrote:
Hello, I need to block current thread, waiting for flag/event. Plz give advice.....
where I`m correct/incorrect ?
Generally you should call wait in a loop (the thread may be notified before you want wait to return). You should usually call notifyAll rather than notify, unless you have a good reason not to. A thread must own an object's monitor to call wait or notify, so you need to synchronize these calls (not necessarily the whole method, but you need to make sure the flag does not change between the evaluation of the while condition and the call to wait).
This should work:
private volatile flag = false;
public synchronized void blockingCall()
{
while (!flag) // Loop so this method doesn't return before the flag is true.
{
try
{
wait();
}
catch (InterruptedException ex)
{
// Ignore and loop again until the flag is true.
}
}
}
/** * Call this from another thread while the above method is blocking * to make it return. */ public synchronized void unblock() { flag = true; notifyAll(); }
Dan.
-- Daniel Dyer http://www.footballpredictions.net .
- Follow-Ups:
- Re: blocking calls in java
- From: Daniel Dyer
- Re: blocking calls in java
- References:
- blocking calls in java
- From: Gyro
- blocking calls in java
- Prev by Date: starting threads from servlets
- Next by Date: Re: starting threads from servlets
- Previous by thread: blocking calls in java
- Next by thread: Re: blocking calls in java
- Index(es):
Relevant Pages
|