Java Reference
In-Depth Information
}
}
Note that the interrupting thread must know which thread to interrupt; logic for track-
ing this relationship has been omitted from this solution.
Noncompliant Code Example (
Thread.getState()
)
This noncompliant code example contains a
doSomething()
method that starts a thread.
The thread supports interruption by checking a flag and waits until notified. The
stop()
method checks to see whether the thread is blocked on the wait; if so, it sets the flag to
true and notifies the thread so that the thread can terminate.
public class Waiter {
private Thread thread;
private boolean flag;
private final Object lock = new Object();
public void doSomething() {
thread = new Thread(new Runnable() {
@Override public void run() {
synchronized (lock) {
while (!flag) {
try {
lock.wait();
// ...
} catch (InterruptedException e) {
// Forward to handler