Thread Interrupt Stops A Sleeping Worker
Stop a long-running worker with Thread.interrupt: the loop checks isInterrupted, the blocking sleep throws InterruptedException, and the flag gets restored.
Code
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CancellableWorker {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
// 中断是协作式的:任务自己查 isInterrupted 标志决定何时退出
executor.submit(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
TimeUnit.MILLISECONDS.sleep(10); // 可中断的阻塞点
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 恢复标志再退出
break;
}
}
System.out.println("worker stopped: interrupted="
+ Thread.currentThread().isInterrupted());
});
TimeUnit.MILLISECONDS.sleep(50);
executor.shutdownNow(); // 向所有任务发送中断信号
executor.awaitTermination(1, TimeUnit.SECONDS);
}
}How the snippet works
Thread Interrupt Stops A Sleeping Worker keeps everything in the class CancellableWorker.
Repetition is confined to while (!Thread.currentThread().isInterrupted()) — the rest of the file is straight-line.
Using it
Look for the worker stopped: interrupted= prefixes when the file runs; they tie each line to its step.
Key statements
ExecutorService executor = Executors.newSingleThreadExecutor();
while (!Thread.currentThread().isInterrupted()) {
try {
TimeUnit.MILLISECONDS.sleep(10); // 可中断的阻塞点
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 恢复标志再退出
break;
}
}
Interactive Tools for This Topic
FAQ
- What does Thread Interrupt Stops A Sleeping Worker print when run?
- No setup needed: run the file and look for labeled lines like `worker stopped: interrupted=` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.