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 测试运行结果:

  • 相关阅读:
    Kali Linux下安装配置ProFTPD实例
    mysql 如何用root 登录
    串口总是报'Error opening serial port'
    用SPCOMM 在 Delphi中实现串口通讯 转
    delphi中使用spcomm来实现串口通讯(转载)
    SPCOMM的一些用法注意
    MySQL 字符串 转 int/double CAST与CONVERT 函数的用法
    彻底删除mysql服务
    mysql 非安装版的一个自动安装脚本及工具(更新版)
    bat操作数据库mysql
  • 原文地址:https://www.cnblogs.com/mjtabu/p/12694964.html
Copyright © 2011-2022 走看看