• 并发编程:为何线程的等待方法都会抛出InterruptException


    线程中的Interrupt

    线程中存在volatile变量Interrupt,用来标记是否中断。
    线程中存在对应的isInterrupted()方法,默认是false。调用thread.interrupt()会把isInterrupted()设置成true。

    线程的中断和复位

    调用thread.interrupt()会把isInterrupted()设置成true。那么其如何复位呢?
    1、Thread.interrupted() 返回当前状态复位,回复到初始状态(false)。注意这是一个静态方法。
    Demo

    public static void main(String[] args) {
            Thread thread = new Thread(() -> {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("before :" + Thread.currentThread().isInterrupted());
                        System.out.println("before :" + Thread.currentThread().isInterrupted());
                        //返回当前状态并复位
                        boolean interrupted = Thread.interrupted();
                        System.out.println(interrupted);
                        System.out.println("after :" + Thread.currentThread().isInterrupted());
                        System.out.println("after :" + Thread.currentThread().isInterrupted());
                    }
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            thread.interrupt();
        }
    

    会打印

    before : true
    before : true
    after : false
    after : false
    

    2、InterruptedException
    Demo

    public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        //直接中断休眠中的线程,复位并抛出异常
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            TimeUnit.SECONDS.sleep(1);
            thread.interrupt();
    
            System.out.println(thread.isInterrupted());
        }
    
  • 相关阅读:
    开始逆向objc基础准备(一)简单认识一下arm32,以及与x86汇编指令类比
    构思一个在windows下仿objc基于动画层ui编程的ui引擎
    设计模式学习笔记整理手册
    面向对象的设计原则
    Oracle和Mysql获取uuid的方法对比
    设计模式之解释器模式(行为型)
    设计模式之命令模式(行为型)
    设计模式之中介者模式(行为型)
    设计模式之迭代器模式(行为型)
    Delphi
  • 原文地址:https://www.cnblogs.com/fcb-it/p/13277056.html
Copyright © 2020-2023  润新知