How to properly interrupt a thread in Java?
In Java, there are typically two ways to properly interrupt a thread.
- By using the interrupt() method, calling the interrupt() method of the thread object can interrupt the thread. When a thread is interrupted, it sets the thread’s interrupt status to true and throws an InterruptedException. During thread execution, you can determine whether to continue or stop the thread by checking the interrupt flag.
Here is an example code:
Thread thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 执行线程逻辑
}
});
thread.start();
// 中断线程
thread.interrupt();
- Utilizing either a volatile variable or an AtomicBoolean variable: You can use a volatile variable or an AtomicBoolean variable to control whether a thread should continue executing. To interrupt a thread, simply change the value of this variable, and the thread can determine whether to continue executing by checking the value of the variable.
The example code is as follows:
volatile boolean flag = true;
Thread thread = new Thread(() -> {
while (flag) {
// 执行线程逻辑
}
});
thread.start();
// 中断线程
flag = false;
It is important to note that interrupting a thread does not mean the thread will immediately stop. Instead, after setting the interrupt flag, the thread can decide whether to stop execution based on the interrupt flag. When writing thread logic, it is necessary to check the interrupt flag at the appropriate places to ensure the thread can respond to interrupts correctly.