InterruptedException与interrupt()方法简单说明

InterruptedException在如下场景下会发生,即使用sleep(),wait(),join()方法时

package com.java.test.Interrupted.expection;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2022/10/26 11:01
 */
@Slf4j
public class ThreadTest extends Thread{

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

  

package com.java.test.Interrupted.expection;

/**
 * @Description:
 * @Author: Yourheart
 * @Create: 2022/10/26 10:54
 */
public class InterruptedTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadTest threadTest = new ThreadTest();
        threadTest.start();
        Thread.sleep(10);
        threadTest.interrupt();
        Thread.sleep(100);
        System.exit(0);
    }
}

能够被中断的阻塞为轻量级阻塞,对应的线程状态为WAITING或者TIMED)WAITING

像synchronized不能被中断的阻塞称为重量级阻塞,对应的状态为BLOCKED

 

 线程在创建完成后,会进入RUNNING和READY两种状态,当调用阻塞函数(wait,join,park,sleep)后,线程根据不同的情况进入两种不同的状态,一种是WAITING,另一种是TIMED_WAITING,两者的不同之处在于,前者是无限阻塞,后者的阻塞是有时间限制的

因此thread.interrupt()的真实含义是唤醒轻量级的阻塞

下面给出thread.isInterrupted()和Thread.Interrupted()的区别,前者需要创建对象然后去调用,返回当前线程是否被中断了,只是获取状态值,不会重置线程的状态,后者是静态方法,会清除线程的状态

 

 

 

 验证代码

package com.java.test.Interrupted.expection;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author qiuxie
 * @Date 2022/10/26 22:49
 */
@Slf4j
public class UpgradeThread extends Thread {

    @Override
    public void run() {
        int i = 0;
        while (true) {
            boolean interrupted = isInterrupted();
            log.info("中断标记:{}",interrupted);
            ++i;
            if (i > 200) {
                // 检查并重置中断标志。
                boolean interrupted1 = Thread.interrupted();
                log.info("重置中断状态:{}",interrupted1);
                interrupted1 = Thread.interrupted();
                log.info("重置中断状态:{}",interrupted1);
                interrupted = isInterrupted();
                log.info("中断标记:{}",interrupted);
                break;
            }
        }


    }
}

  

package com.java.test.Interrupted.expection;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description
 * @Author qiuxie
 * @Date 2022/10/26 22:49
 */
@Slf4j
public class UpgradeTest {

    public static void main(String[] args) throws InterruptedException {
        UpgradeThread upgradeThread=new UpgradeThread();
        upgradeThread.start();
        Thread.sleep(10);
        upgradeThread.interrupt();
        Thread.sleep(7);
        log.info("中断状态检查-1:{}",upgradeThread.isInterrupted());
        log.info("中断状态检查-2:{}",upgradeThread.isInterrupted());

    }
}

  

posted @ 2022-10-26 22:57  不忘初心2021  阅读(41)  评论(0编辑  收藏  举报