Java.lang.Thread.setName() 方法
描述
java.lang.Thread.setName() 方法将此线程的名称更改为等于参数 name。
声明
以下是 java.lang.Thread.setName() 方法的声明。
public final void setName(String name)
参数
name − 这是此线程的新名称
返回值
此方法不返回任何值。
异常
SecurityException − 如果当前线程不能修改这个线程。
示例
下面的例子展示了 java.lang.Thread.setName() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class ThreadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
// prints the thread name
System.out.println("Thread = " + t);
// change the thread name
t.setName("Admin Thread");
// prints the thread after changing name
System.out.println("Thread after changing name = " + t);
int count = Thread.activeCount();
System.out.println("currently active threads = " + count);
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Thread = Thread[main,5,main] Thread after changing name = Thread[Admin Thread,5,main] currently active threads = 1

