• 【java】3-获取线程引用与线程的属性


    1.获取线程的引用

    在创建一个线程之后,我们很有必要去获取当前线程实例的引用,以便能够观察到线程的一些属性,或是对于当前线程进行一系列的操作

    调用Thread类的静态方法currentThread,我们便能拿到当前线程的引用

    Thread.currentThread()
    
    • 1

    通过线程的引用,我们便可以调用当前线程引用的一些方法,获取线程的一些信息

    public class Demo11 {
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(()->{
                System.out.println(Thread.currentThread().getId());
                System.out.println(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getState());
                System.out.println(Thread.currentThread().getPriority());
                System.out.println(Thread.currentThread().isDaemon());
                System.out.println(Thread.currentThread().isAlive());
                System.out.println(Thread.currentThread().isInterrupted());
            });
            t1.start();
            Thread.sleep(1000);
            System.out.println("====================================");
            Thread t2 = new Thread(()->{
                System.out.println(Thread.currentThread().getId());
                System.out.println(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getState());
                System.out.println(Thread.currentThread().getPriority());
                System.out.println(Thread.currentThread().isDaemon());
                System.out.println(Thread.currentThread().isAlive());
                System.out.println(Thread.currentThread().isInterrupted());
            });
            t2.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    运行结果:
    在这里插入图片描述

    2.获取线程实例属性的一些方法

    属性获取属性的方法用途
    IDgetId()ID 是线程的唯一标识,不同线程不会重复
    名称getName()名称在使用调试工具时候会用到
    状态getState()状态表示线程当前所处的一个情况
    优先级getPriority()优先级高的线程理论上来说更容易被调度到
    是否为后台线程isDaemon()JVM会在一个进程的所有非后台线程结束后,才会结束运行
    是否存活isAlive()是否存活,即简单的理解为 run 方法是否运行结束了
    是否被中断isInterrupted()判断一个线程是否被中断
  • 相关阅读:
    MATLAB与Excel的数据交互
    【linux kernel】linux内核设备驱动的注册机制
    前端无感登录(无感刷新token)
    Linux 中的 chpasswd 命令及示例
    湘潭大学大三上选修数据库 实验九—游标
    asp.net上传文件
    软件加密系统Themida应用程序保护指南(九):通过命令行进行保护
    云原生底座之上,顺丰智慧供应链领跑的秘密
    【ccf-csp题解】第5次csp认证-第三题-模板生成系统-字符串模拟
    SpringBoot+Mybaits搭建通用管理系统实例九:基础增删改查功能实现上
  • 原文地址:https://blog.csdn.net/m0_52640673/article/details/128167946