包java.lang.Thread.getId()中提供了此方法。
此方法用于返回此线程的ID(标识符)。
此方法不是静态的,因此该方法可通过Thread类对象访问,而无法通过类名称访问。
每个线程都有一个唯一的ID,并在线程实例化时创建ID。
即使线程终止,我们也无法更改线程的ID,并且ID可能会再次重用。
此方法不会引发任何异常。
语法:
long getId(){
}参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
此方法的返回类型为long,它返回此线程的ID,并且ID为长整数类型。
getId()方法示例/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class GetThreadId extends Thread {
//覆盖run()Thread类
public void run() {
System.out.println("The priority of this thread is : " + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
//创建一个GetThreadId类的对象
GetThreadId gt_id = new GetThreadId();
//start()使用GetThreadId类的调用方法
//Thread类的对象
gt_id.start();
//获取线程名称并显示在标准位置
//输出流
System.out.println("The name of this thread is " + " " + gt_id.getName());
//获取线程的ID并显示在标准
//输出流
System.out.println("The Id of this thread is " + " " + gt_id.getId());
}
}输出结果
E:\Programs>javac GetThreadId.java E:\Programs>java GetThreadId The priority of this thread is :5 The name of this thread is Thread-0 The Id of this thread is 9