zoukankan      html  css  js  c++  java
  • 并发编程:为何线程的等待方法都会抛出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());
        }
    
  • 相关阅读:
    layui formSelects-v4复选框总结等table操作记
    C# 更改 WebBrowser UserAgent
    SQL Server 页撕裂
    c# 实现操作系统 “运行” 功能
    asp.net updatepanel 客户端事件
    javascript des 加密解密
    无日志文件还原数据库(只有mdf无ldf)
    关于 WebForm 在未来微软的替代方案
    C# 从32位程序启动64位程序
    SQL SERVER 数据库修复方法 (数据库变为 "可疑")
  • 原文地址:https://www.cnblogs.com/fcb-it/p/13277056.html
Copyright © 2011-2022 走看看