How to use the thread interrupt method in Java?
In Java, you can interrupt a thread using the interrupt() method of the Thread class. The syntax of this method is as follows:
public void interrupt()
To utilize this method, you must first create a Thread object and then call the interrupt() method at the point where you want to interrupt the thread. Once the thread is interrupted, its interrupt status will be set to true.
Here is a simple example demonstrating how to interrupt a thread using the interrupt() method.
public class MyThread extends Thread {
public void run() {
try {
// 在这里执行线程的任务
// 使用Thread.sleep()模拟一个耗时的操作
for (int i = 0; i < 10; i++) {
System.out.println("执行任务...");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("线程被中断!");
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
// 在某个时间点上中断线程
try {
Thread.sleep(5000); // 等待5秒
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In the above example, we created a custom thread class named MyThread that inherits from the Thread class. In the run() method, we used Thread.sleep() method to simulate a time-consuming operation. In the main thread, we created a MyThread object and called its start() method to start the thread. Then, we waited for 5 seconds and then called thread.interrupt() to interrupt the thread. When the thread is interrupted, it will throw an InterruptedException and handle the interrupt situation in the catch block.
It is important to note that the interrupt() method only sends a interrupt request to a thread, and the specific interrupt handling logic needs to be implemented in the thread’s run() method. You can use the isInterrupted() method in the run() method to check the thread’s interrupt status and decide whether to terminate the thread’s execution.
Moreover, the static method Thread.interrupted() can be used to check the interruption status of the current thread and clear the interrupt status. This method will return the interrupt status of the current thread and reset the interrupt status to false.