在java中,使用interrrupt可以用来请求中止线程。对一个线程调用interrrupt方法时,该线程的中断状态位被置位,每个线程不断访问自己的这个标志,以判断线程是否被中断(只是要求java开发者去添加的判断,并不在内部实现)。可以调用Thread的方法isInterrupted判断是否线程中断,代码如下:
//5s后interrup请求打印一个异常
public class Main {public static void main(String[] args) {Thread thread = new Thread(() -> {while (!Thread.currentThread().isInterrupted()) {System.out.println("Hello World");}});thread.start();try {Thread.sleep(5000);thread.interrupt();} catch (InterruptedException e) {e.printStackTrace();}}
}
线程在5s后得到中断请求,中断。停止打印。
如果线程被阻塞,处于sleep或wait状态,则在请求该线程中断时,会抛出InterruptedException,代码如下:
//5s后interrup请求打印一个异常
public class Main {public static void main(String[] args) {Thread thread = new Thread(()->{while(!Thread.currentThread().isInterrupted()){try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Hello World");}});thread.start();try {Thread.sleep(5000);thread.interrupt();} catch (InterruptedException e) {e.printStackTrace();}}
}