https://blog.csdn.net/zhangliangzi/article/details/52485319
API
| void | interrupt() 打断这个线程,异常处理机制 |
|---|---|
| static boolean | interrupted() 判断当前线程是否被打断,打断返回 true,清除打断标记,连续调用两次一定返回 false |
| boolean | isInterrupted() 判断当前线程是否被打断,不清除打断标记 打断的线程会发生上下文切换,操作系统会保存线程信息,抢占到 CPU 后会从中断的地方接着运行 |
interrupt()
interrupt() 方法只是改变中断状态而已,它不会中断一个正在运行的线程。这一方法实际完成的是,给受阻塞的线程发出一个中断信号,这样受阻线程就得以退出阻塞的状态。 更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,此时调用该线程的interrupt()方法,那么该线程将抛出一个 InterruptedException中断异常(该线程必须事先预备好处理此异常),从而提早地终结被阻塞状态,此时的interrupted() 方法返回的是false。如果线程没有被阻塞,这时调用 interrupt()将不起作用也就是当前线程并不会终止,直到执行到wait(),sleep(),join()时,才马上会抛出 InterruptedException。
线程A在执行sleep,wait,join时,线程B调用线程A的interrupt方法,的确这一个时候A会有 InterruptedException 异常抛出来。但这其实是在sleep,wait,join这些方法内部会不断检查中断状态的值,而自己抛出的InterruptedException。 如果线程A正在执行一些指定的操作时如值,for,while,if,调用方法等,不会去检查中断状态,则线程A不会抛出 InterruptedException,而会一直执行着自己的操作。
处于阻塞状态下,打断是不会更改中断状态的。可以在异常处理catch模块中再次调用 interrupt方法改变中断状态
打断阻塞线程代码:
public static void main(String[] args) {final Thread lin =new Thread() {public void run() {System.out.println("林:刚美容完,睡一会儿吧。");try {Thread.sleep(1000000);System.out.println("林:伸伸懒腰!");} catch (InterruptedException e) {System.out.println("林:干嘛呢!干嘛呢!干嘛呢!都破了相了!");}System.out.println("林:醒了!");}};Thread huang =new Thread() {public void run() {System.out.println("黄:开始砸墙!");for (int i = 0; i < 5; i++) {System.out.println("黄:80!");try {Thread.sleep(1000);} catch (InterruptedException e) {}}System.out.println("咣当!");System.out.println("黄:搞定!");lin.interrupt(); // 打断lin线程}};lin.start();huang.start();}
打断非阻塞线程代码:
public void method1() throws InterruptedException {Thread t =new Thread(() -> {while (true) {boolean state = Thread.currentThread().isInterrupted(); // 获取打断标示if (state) {System.out.println("我被打断了,我即将推出循环");break;}}});t.start();Thread.sleep(100);t.interrupt(); // 打断System.out.println(t.isInterrupted());//true,但是t线程并没有终止}
