• 四、LockSupport与线程中断


    一、线程中断机制

    1、什么是中断

    1、中断可以理解为线程的一个标志位,它表示了一个运行中的线程是否被其他线程进行了中断操作。中断好比其他线程对该线程打了一个招呼,其他线程通过调用该线程的interrupt方法对其进行中断操作,同时该线程可以调用isInterrupted来感知其他线程对其自身的中断操作,从而做出响应。
    2、调用interrupt方法仅仅是将线程对象的中断标识设置成true,每个线程对象中都有一个中断标识位,用于表示线程是否被中断,该标识位true表示中断,false表示未中断
    3、另外,同样可以调用Thread的静态方法interrupted对当前线程进行中断操作,该方法会清除中断标志位。
    3、注意:当抛出InterruptedException的时候,会清除中断标志位,也就是说在调用isInterrupted会返回fasle

    2、中断的相关方法

    1、public void interrupt():仅仅是设置线程的中断状态为true,不会停止线程,需要注意如下两点:
    • 当对一个线程调用interrupt方法时,如果被打断线程处于被阻塞状态(如:sleep、wait、join等状态),会导致被打断的线程抛出InterruptedException,退出被阻塞状态,并清除打断标记
    • 如果被打断的线程处于活跃状态,则会将线程的中断标识设置为true,被设置中断标识的线程将继续运行,不受影响;因此interrupt并不能真正的中断线程,需要设置为中断标识的线程自己进行处理,才能中断线程。
    • park的线程被打断,也会设置打断标记
    2、public static boolean interrupted():Thread类的静态方法,判断线程是否被中断,并清除当前中断标识位,这个方法干了两件事:
    • 返回当前线程的中断状态
    • 将当前线程的中断状态设置为false
    3、public boolean isInterrupted():获取线程中断标识位的当前值,用于判断当前线程是否被中断,默认是false。

    3、中断线程的几种方法

    1、通过一个volatile变量实现
    2、通过AtomicBoolean原子类实现
    3、通过Thread类自带的中断方法实现
    /**
     * @Date: 2022/7/18
     * 通过volatile中断停止线程
     */
    public class Inter1 {
        static volatile boolean flag = false;
    
        public static void main(String[] args) throws InterruptedException {
            new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (flag) {
                        System.out.println(Thread.currentThread().getName() + "停止运行,flag为:" + flag);
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "正在运行,flag为:" + flag);
                }
            }, "t1").start();
    
            Thread.sleep(1000);
    
            new Thread(() -> {
                flag = true;
                System.out.println(Thread.currentThread().getName() + "将flag修改为:" + true);
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:
     * t1正在运行,flag为:false
     * t1正在运行,flag为:false
     * t1正在运行,flag为:false
     * t1正在运行,flag为:false
     * t2将flag修改为:true
     * t1停止运行,flag为:true
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    /**
     * @Date: 2022/7/18
     * 通过AtomicBoolean中断停止线程
     */
    public class Inter2 {
        static AtomicBoolean flag = new AtomicBoolean(false);
    
        public static void main(String[] args) throws InterruptedException {
            new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (flag.get()) {
                        System.out.println(Thread.currentThread().getName() + "停止运行,flag为:" + flag);
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "正在运行,flag为:" + flag);
                }
            }, "t1").start();
    
            Thread.sleep(1000);
    
            new Thread(() -> {
                flag.compareAndSet(false, true);
                System.out.println(Thread.currentThread().getName() + "将flag修改为:" + true);
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:
     * t1正在运行,flag为:false
     * t1正在运行,flag为:false
     * t1正在运行,flag为:false
     * t1正在运行,flag为:false
     * t2将flag修改为:true
     * t1停止运行,flag为:true
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    /**
     * @Date: 2022/7/18
     * 通过Thread中断API停止线程
     */
    public class Inter3 {
    
        public static void main(String[] args) {
            Thread t1 = new Thread(() -> {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println(Thread.currentThread().getName() + "停止运行,中断标识位为:" + Thread.currentThread().isInterrupted());
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "正在运行,中断标识位为" + Thread.currentThread().isInterrupted());
                }
            }, "t1");
            t1.start();
    
            new Thread(() -> {
                //打断t1线程
                t1.interrupt();
                System.out.println(Thread.currentThread().getName() + "将t1线程的中断标识位设置为:" + true);
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:
     * t1正在运行,中断标识位为false
     * t1正在运行,中断标识位为false
     * t1正在运行,中断标识位为false
     * t1正在运行,中断标识位为false
     * t2将t1线程的中断标识位设置为:true
     * t1停止运行,中断标识位为:true
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    4、interrupt与isInterrupted的源码

    1、interrupt方法:

    在这里插入图片描述

    2、isInterrupted方法:

    在这里插入图片描述

    5、interrupt被清除中断标识的情况

    1、如果被打断线程处于被阻塞状态(如:sleep、wait、join等状态),会导致被打断的线程抛出InterruptedException,退出被阻塞状态,并清除打断标记
    /**
     * @Date: 2022/7/18
     * 线程处于sleep、wait、join等状态被打断,抛出InterruptedException,并清除中断标识
     */
    public class Inter4 {
    
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(() -> {
                while (true) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                         System.out.println(Thread.currentThread().getName() + "出现异常后,中断标识位为:" + Thread.currentThread().isInterrupted());
                        /**
                         * 当出现InterruptedException异常的时候,中断标识被清除(false),导出程序无法停止,进入死循环
                         * Thread.currentThread().interrupt();再次将中断标识设置为true
                         */
                        Thread.currentThread().interrupt();
                        e.printStackTrace();
                    }
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println(Thread.currentThread().getName() + "停止运行,中断标识位为:" + Thread.currentThread().isInterrupted());
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "正在运行,中断标识位为" + Thread.currentThread().isInterrupted());
                }
            }, "t1");
            t1.start();
    
            Thread.sleep(1000);
    
            new Thread(() -> {
                //打断t1线程
                t1.interrupt();
                System.out.println(Thread.currentThread().getName() + "将t1线程的中断标识位设置为:" + true);
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:可以看到出现异常后,中断标识为false,如果不再打断一次,程序不会停止,会死循环
     * t1正在运行,中断标识位为false
     * t1正在运行,中断标识位为false
     * t1正在运行,中断标识位为false
     * t1正在运行,中断标识位为false
     * t2将t1线程的中断标识位设置为:true
     * t1出现异常后,中断标识位为:false
     * t1停止运行,中断标识位为:true
     * java.lang.InterruptedException: sleep interrupted
     * 	at java.lang.Thread.sleep(Native Method)
     * 	at com.itan.interrupt.Inter4.lambda$main$0(Inter4.java:14)
     * 	at java.lang.Thread.run(Thread.java:748)
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    二、LockSupport

    1、概述

    1、LockSupport用来创建锁和其他同步类的基本线程阻塞原语。是一个线程阻塞工具类,所有的方法都是静态方法,可以让线程任意位置阻塞,阻塞之后有对应的唤醒方法,底层调用Unsafe中的native代码

    在这里插入图片描述

    2、LockSupport类使用了一种名为permit(许可)的概念来做到阻塞和唤醒线程的功能,每个线程都有一个许可(permit,最多只有一个,重复unpark不会累加凭证),它只有两个值1和0,默认是0。
    3、当调用LockSupport.park时,表示当前线程将会等待,直至获得许可,当调用LockSupport.unpark时,必须把等待获得许可的线程作为参数进行传递,好让此线程继续运行

    2、让线程等待和唤醒的方法

    1、使用Object中的wait方法让线程等待,使用notify方法唤醒线程。
    2、使用JUC包中Condition的await方法让线程等待,使用signal方法唤醒线程。
    3、LockSupport类可以阻塞当前线程以及唤醒指定的被阻塞的线程。

    3、wait和notify方法实现线程等待和唤醒

    1、调用wait方法使得线程等待某个条件满足,线程在等待时会被挂起,当其他线程的运行使得这个条件满足时,其它线程会调用notify或者notifyAll方法来唤醒挂起的线程。
    2、只能在同步方法或者同步块中使用,否则在运行时抛出IllegalMonitorStateExeception异常

    在这里插入图片描述

    3、使用wait方法挂起期间,线程会释放锁。这是因为,如果没有释放锁,那么其它线程就无法进入对象的同步方法或者同步块中,那么就无法执行notify方法或notifyAll方法来唤醒挂起的线程,造成死锁
    4、wait和notify必须成对出现使用,先wait后notify才有效
    /**
     * @Date: 2022/7/20
     * 正确使用wait与notify实现线程等待与唤醒
     */
    @Slf4j
    public class LockSupportTest1 {
        public static void main(String[] args) {
            Object objectLock = new Object(); //同一把锁,类似资源类
            new Thread(() -> {
                log.info(Thread.currentThread().getName() + "开始执行");
                synchronized (objectLock) {
                    try {
                        //等待
                        objectLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info(Thread.currentThread().getName() + "线程被唤醒了");
            }, "t1").start();
    
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            new Thread(() -> {
                synchronized (objectLock) {
                    //唤醒
                    objectLock.notify();
                }
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:t1线程在运行2后被t2线程唤醒继续执行
     * 23:49:21.669 [t1] INFO com.itan.locksupport.LockSupportTest1 - t1开始执行
     * 23:49:23.667 [t1] INFO com.itan.locksupport.LockSupportTest1 - t1线程被唤醒了
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    4、Condition接口的await和signal方法

    1、Condition是一个多线程协调通信的工具类,可以让某些线程一起等待某个条件(condition),只有满足条件时,线程才会被唤醒。
    2、Condition对象是由Lock对象(调用Lock对象的newCondition方法)创建的,也就是说Condition是依赖Lock对象的
    3、当调用await方法后,当前线程会释放锁并在此等待,而其他线程调用Condition对象signal方法,通知当前线程后,当前线程才从await方法返回,并且在返回前已经获取了锁
    4、在调用方法前必须获取到锁,否则会抛出IllegalMonitorStateExeception异常
    /**
     * @Date: 2022/7/20
     * 正确使用Condition实现线程等待与唤醒
     */
    @Slf4j
    public class LockSupportTest2 {
        public static void main(String[] args) {
            //创建Lock对象
            Lock lock = new ReentrantLock();
            //通过lock.newCondition创建Condition对象
            Condition condition = lock.newCondition();
            new Thread(() -> {
                //加锁
                lock.lock();
                try {
                    log.info(Thread.currentThread().getName() + "开始执行");
                    //等待
                    condition.await();
                    log.info(Thread.currentThread().getName() + "线程被唤醒了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放锁
                    lock.unlock();
                }
            }, "t1").start();
    
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            new Thread(() -> {
                //加锁
                lock.lock();
                try {
                    //唤醒
                    condition.signal();
                    log.info(Thread.currentThread().getName() + "线程通知唤醒");
                } finally {
                    //释放锁
                    lock.unlock();
                }
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:t1线程在运行2后被t2线程唤醒继续执行
     * 00:15:13.357 [t1] INFO com.itan.locksupport.LockSupportTest2 - t1开始执行
     * 00:15:15.364 [t2] INFO com.itan.locksupport.LockSupportTest2 - t2线程通知唤醒
     * 00:15:15.364 [t1] INFO com.itan.locksupport.LockSupportTest2 - t1线程被唤醒了
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    5、LockSupport类中的park和unpark方法

    1、阻塞方法:park()阻塞当前线程或park(Object blocker)阻塞传入的具体线程
    • 由于permit默认是0,所以一开始调用park()方法,当前线程就会阻塞,直到别的线程将当前线程的permit设置为1时,park方法会被唤醒,然后会将permit再次设置为零并返回。
    2、唤醒方法:unpark(Thread thread)唤醒处于阻塞状态的指定线程
    • 调用unpark(thread)方法后,就会将thread线程的许可permit设置成1(注意多次调用unpark方法,不会累加,permit值还是1)会自动唤醒thread线程,即之前阻塞中的LockSupport.park()方法会立即返回。
    3、相对于前面两种方法,LockSupport无需加锁就能实现等待和唤醒
    4、LockSupport不仅支持先等待后唤醒,而且也支持先唤醒后等待,如果是先唤醒,就不会再阻塞线程的执行了
    /**
     * @Date: 2022/7/20
     * 正确使用LockSupport实现线程等待与唤醒
     */
    @Slf4j
    public class LockSupportTest3 {
        public static void main(String[] args) {
            Thread t1 = new Thread(() -> {
                log.info(Thread.currentThread().getName() + "开始执行");
                //等待
                LockSupport.park();
                log.info(Thread.currentThread().getName() + "线程被唤醒了");
            }, "t1");
            t1.start();
    
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            new Thread(() -> {
                log.info(Thread.currentThread().getName() + "线程通知唤醒");
                //唤醒
                LockSupport.unpark(t1);
            }, "t2").start();
        }
    }
    /**
     * 运行结果如下:t1线程在运行2后被t2线程唤醒继续执行
     * 23:52:53.771 [t1] INFO com.itan.locksupport.LockSupportTest3 - t1开始执行
     * 23:52:55.767 [t2] INFO com.itan.locksupport.LockSupportTest3 - t2线程通知唤醒
     * 23:52:55.768 [t1] INFO com.itan.locksupport.LockSupportTest3 - t1线程被唤醒了
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    6、总结

    1、使用Object类中wait、notify方法让线程等待和唤醒,以及Condition接口中await、signal方法让线程等待和唤醒的前提:
    • 线程首先要获得并持有锁,必须在synchronized或lock中
    • 必须要先等待后唤醒,线程才能被唤醒
    2、LockSupport无需加锁就能实现等待和唤醒,不仅支持先等待后唤醒,而且也支持先唤醒后等待,如果是先唤醒,就不会再阻塞线程的执行了。
    3、对LockSupport唤醒两次后阻塞两次,最终还会阻塞线程的解释:
    • 因为permit的数量最多为1,连续调用两次unpark和调用一次unpark效果一样,只会增加一个凭证。
    • 连续调用两次park却需要消费两个凭证,因此凭证不够,阻塞线程。
  • 相关阅读:
    ListenableFuture和countdownlatch使用example
    consul--基础--04--命令
    1144 The Missing Number
    数据结构之<RBTree >
    动态链接那些事
    OpenCV图像处理——图像梯度
    钉钉打卡作弊软件非法获利近 500 万元,CEO 被判刑 5 年 6 个月
    README.md文件使用
    阿里云ARMS监控
    C++ lambda表达式
  • 原文地址:https://blog.csdn.net/qq_42200163/article/details/126474290