zoukankan      html  css  js  c++  java
  • Thread的Interrupt、isInterrupted、interrupted

    线程中断:Interrupt、isInterrupted、interrupted

    线程并不是抢占式的,线程是协作式的。

    • Interrupt:声明此线程中断,但是线程并不会立即中断;

    • isInterrupted:判断此线程是否已中断,判断完后不修改线程的中断状态;

    • interrupted:判断此线程是否已中断,判断完后清除线程的中断状态

    线程的中断状态默认为( isInterrupted=false interrupted=false ),也就是默认不中断线程

    Interrupt理解:

    中断线程(isInterrupted=true)

    就比如皇上(线程)每晚挑选一个妃子侍寝,到了时间,太监会告诉皇上(线程),时间到了(声明线程中断),皇上(线程)知道了,但是动作停不停还是皇上(线程)说了算,可以不理会,也可以收手。

    isInterrupted理解:

    判断是否中断线程,如果(isInterrupted=true)则可以控制皇上(线程)收手(停止);皇上(线程)收手(停止)后,线程还是中断状态,也就是(isInterrupted=true);

    interrupted理解:

    判断是否中断线程,如果(interrupted=true)则可以控制皇上(线程)收手(停止);皇上(线程)收手(停止)后,线程会清楚中断状态,也就是(isInterrupted=false);

    测试代码

    public class TheadInterrupt {
    
        //线程继承Thread类
        private static class UserThread extends Thread{
            public UserThread(String name){
                super(name);
            }
            @Override
            public void run() {
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName+"Thread=start=interrupt:"+isInterrupted());
                //测试线程中断
                while (!isInterrupted()){//打开测试isInterrupted
                //while (!interrupted()){//打开测试interrupted
                    System.out.println(threadName+"Thread=while=interrupt:"+isInterrupted());
                }
                System.out.println(threadName+"Thread=end=interrupt:"+isInterrupted());
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            UserThread userThread = new UserThread("mjtabu");
            userThread.start();
            //线程睡眠 n 毫秒(时间可调)
            userThread.sleep(2);
            //睡眠 n 毫秒后线程中断
            userThread.interrupt();
        }
    }

    isInterrupted 测试运行结果:

    interrupted 测试运行结果:

  • 相关阅读:
    [个人]工作中的死亡陷阱
    [阮一峰]在软件开发中,一旦这些技术被取代,你的知识将变得毫无价值,因为它们大部分都是实施的细节。
    [原文 + 补充] 当你在浏览器中输入Google.com并且按下回车之后发生了什么?
    安全的知识点总结
    purge旧的ubuntu 的linux内核
    【个人】运维常识
    windows数字证书管理器
    在mobaxterm内连接deb使用lrzsz进行文件传输
    网络安全常见考试题
    linux deb系 rpm系 配置路由
  • 原文地址:https://www.cnblogs.com/mjtabu/p/12694964.html
Copyright © 2011-2022 走看看