getName()包java.lang.Thread.getName()中提供了此方法。
此方法用于返回该线程的名称。
此方法不是静态的,因此该方法可通过Thread类对象访问,而无法通过类名称访问。
此方法是最终方法,因此我们无法在程序中覆盖此方法。
该方法的返回类型为String,因此它以字符串的形式返回线程的名称(即Name将在字符串中)。
此方法不会引发任何异常。
语法:
final String getName(){
}参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
该方法的返回类型为String,它以字符串形式返回此线程的名称。
getName()方法示例/* 我们将使用Thread类方法,因此我们将导入包,但不是强制性的,因为默认情况下导入
*/
import java.lang.Thread;
class GetThreadName 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) {
//创建一个GetThreadName类的对象
GetThreadName gt_name = new GetThreadName();
//我们正在设置线程名称GetThreadName-
gt_name.setName("GetThreadName");
/* Calling start() method with GetThreadName class
object of Thread class
*/
gt_name.start();
/* By using getName() method to return the name of
this thread [GetThreadName ]
*/
System.out.println("The name of this thread is " + " " + gt_name.getName());
}
}输出结果
E:\Programs>javac GetThreadName.java E:\Programs>java GetThreadName The name of this thread is GetThreadName The priority of this thread is :5