在创建一个线程之后,我们很有必要去获取当前线程实例的引用,以便能够观察到线程的一些属性,或是对于当前线程进行一系列的操作
调用Thread类的静态方法currentThread,我们便能拿到当前线程的引用
Thread.currentThread()
通过线程的引用,我们便可以调用当前线程引用的一些方法,获取线程的一些信息
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();}
}
运行结果:

| 属性 | 获取属性的方法 | 用途 |
|---|---|---|
| ID | getId() | ID 是线程的唯一标识,不同线程不会重复 |
| 名称 | getName() | 名称在使用调试工具时候会用到 |
| 状态 | getState() | 状态表示线程当前所处的一个情况 |
| 优先级 | getPriority() | 优先级高的线程理论上来说更容易被调度到 |
| 是否为后台线程 | isDaemon() | JVM会在一个进程的所有非后台线程结束后,才会结束运行 |
| 是否存活 | isAlive() | 是否存活,即简单的理解为 run 方法是否运行结束了 |
| 是否被中断 | isInterrupted() | 判断一个线程是否被中断 |