中断机制之中断协商案例深度解析 上

说明

具体来说,当一个线程调用interrupt()时:

  • 如果线程处于正常活动状态,那么会将该线程的中断标志设置为true ,仅此而已。被设置中断标志的线程将继续正常运行,不受影响。所以,innerupt()并不能真正的中断线程,需要被调用的线程自己进行配合才行。
  • 如果线程处于被阻塞状态(例如处于sleep ,wait,join等状态) ,在别的线程中调用当前线程对象的interrupt方法,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常。

案例

实例方法interrupt()仅仅是设置线程的中断状态位为true,不会停止线程

package com.kwfruit.thread.interruptdemo;

import java.util.concurrent.TimeUnit;

public class InterruptDemo2 {


    public static void main(String[] args) {
        //实例方法interrupt()仅仅是设置线程的中断状态位为true,不会停止线程

        Thread t1 = new Thread(()->{

            for (int i =1;i<=300;i++){
                System.out.println("---"+i);
            }

            System.out.println("t1 调用interrupt()后的中断标识02:"+Thread.currentThread().isInterrupted()); //true


        },"t1");
        t1.start();

        System.out.println("t1 线程默认的中断标识:"+t1.isInterrupted()); //false


        try {
            TimeUnit.MILLISECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();//true
        System.out.println("t1 调用interrupt()后的中断标识01:"+t1.isInterrupted()); //true



    }

}


t1 线程默认的中断标识:false
---1
---2
太长了省略
---136
---137
t1 调用interrupt()后的中断标识01:true
---138
---139
---140
太长了省略
---300
t1 调用interrupt()后的中断标识02:true

Process finished with exit code 0


小总结:'t1 调用interrupt()后的中断标识02:true' 这句话能正常输出,说明程序正常运行完毕,并没有中断调 所以验证了实例方法interrupt()仅仅是设置线程的中断状态位为true,不会停止线程

中断不活动的线程不会产生任何影响

package com.kwfruit.thread.interruptdemo;

import java.util.concurrent.TimeUnit;

public class InterruptDemo2 {


    public static void main(String[] args) {
        //实例方法interrupt()仅仅是设置线程的中断状态位为true,不会停止线程

        Thread t1 = new Thread(()->{

            for (int i =1;i<=300;i++){
                System.out.println("---"+i);
            }

            System.out.println("t1 调用interrupt()后的中断标识02:"+Thread.currentThread().isInterrupted()); //true


        },"t1");
        t1.start();

        System.out.println("t1 线程默认的中断标识:"+t1.isInterrupted()); //false


        try {
            TimeUnit.MILLISECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();//true
        System.out.println("t1 调用interrupt()后的中断标识01:"+t1.isInterrupted()); //true

        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("t1 调用interrupt()后的中断标识03:"+t1.isInterrupted()); //false

    }

}


t1 线程默认的中断标识:false
---1
---2
太长了省略
---136
---137
t1 调用interrupt()后的中断标识01:true
---138
---139
---140
太长了省略
---300
t1 调用interrupt()后的中断标识02:true
t1 调用interrupt()后的中断标识03:false

Process finished with exit code 0


小总结:上面程序2000ms之后 程序早已运行完毕 中断标识变为了false 验证了 中断不活动的线程不会产生任何影响

posted @ 2024-01-21 16:49  KwFruit  阅读(1)  评论(0编辑  收藏  举报