在 Java 中显示线程的信息
java 8object oriented programmingprogramming
为了获取线程的名称,我们使用 Java 中的 getName() 方法。此方法返回线程的名称。
声明 − java.lang.Thread.getName() 方法声明如下 −
public String getName()
为了获取线程的身份,我们使用 Java 中的 getId() 方法。此方法返回线程的标识符。线程 ID 是在创建线程期间生成的一个正长数。
声明 − java.lang.Thread.getId() 方法声明如下 −
public long getId()
为了获取线程的状态,我们使用 Java 中的 getState() 方法。此方法返回线程的状态。线程状态旨在检查系统状态,而不是控制同步。
声明 − java.lang.Thread.getState() 方法声明如下 −
public Thread.state getState()
为了获取线程的状态,我们使用 Java 中的 isAlive() 方法。此方法检查线程是否处于活动状态。如果线程已启动且未终止,则称其为活动状态。
声明 − java.lang.Thread.isAlive() 方法声明如下 −
public final boolean isAlive()
我们来看一个获取线程信息的例子 −
示例
public class Example extends Thread { public void run() { for (int k = 0; k <= 5; k++) { print(); } } public void print() { Thread t = Thread.currentThread(); String name = t.getName(); long id = t.getId(); boolean status = t.isAlive(); Thread.State state = t.getState(); System.out.print("Thread name = " + name); System.out.print(" Thread ID = " + id); System.out.print(" Thread State = " + state); System.out.println(" Thread Status = " + status); } public static void main(String[] args) { Example e = new Example(); e.start(); // 调用 run 方法 for (int i = 0; i <= 5; i++) { e.print(); } } }
输出
Thread name = main Thread ID = 1 Thread State = RUNNABLE Thread Status = true Thread name = main Thread ID = 1 Thread State = RUNNABLE Thread Status = true Thread name = main Thread ID = 1 Thread State = RUNNABLE Thread Status = true Thread name = main Thread ID = 1 Thread State = RUNNABLE Thread Status = true Thread name = main Thread ID = 1 Thread State = RUNNABLE Thread Status = true Thread name = main Thread ID = 1 Thread State = RUNNABLE Thread Status = true Thread name = Thread-0 Thread ID = 21 Thread State = RUNNABLE Thread Status = true Thread name = Thread-0 Thread ID = 21 Thread State = RUNNABLE Thread Status = true Thread name = Thread-0 Thread ID = 21 Thread State = RUNNABLE Thread Status = true Thread name = Thread-0 Thread ID = 21 Thread State = RUNNABLE Thread Status = true Thread name = Thread-0 Thread ID = 21 Thread State = RUNNABLE Thread Status = true Thread name = Thread-0 Thread ID = 21 Thread State = RUNNABLE Thread Status = true