为了获得线程的名称,我们使用getName()Java中的方法。此方法返回线程的名称。
声明-java.lang.Thread.getName()方法的声明如下-public String getName()
为了获得线程的标识,我们使用getId()Java中的方法。此方法返回线程的标识符。线程ID是在创建线程期间产生的正长整数。
声明-java.lang.Thread.getId()方法的声明如下-public long getId()
为了获得线程的状态,我们使用getState()Java中的方法。此方法返回线程的状态。线程状态设计用于保持对系统状态的检查,而不是用于控制同步。
声明-java.lang.Thread.getState()方法的声明如下-public Thread.state getState()
为了获得线程的状态,我们使用isAlive()Java中的方法。此方法检查线程是否处于活动状态。如果线程已启动但尚未终止,则该线程被称为活动线程。
声明-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(); // calls the run method
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