本 Java 教程将解释如何在 Java 中设置和获取线程名称。 Thread 类提供了两种处理线程名称的方法。 默认情况下,每个线程都有一个名称,如线程 0、线程 1 和线程 2 等。 但是通过使用 setName()
方法我们可以根据自己的方便设置线程名称,使用 getName()
方法我们可以看到线程名称。
1- public void setName([[$4$]])
– 将线程名称更改为等于参数名称。
2- public String getName()
– 返回线程的名称。
注意:setName()
方法在当前线程无法修改该线程时抛出 SecurityException
。
####设置和获取线程名称的示例
SetThreadNameExp.java
package org.websparrow.thread.methods;
public class SetThreadNameExp extends Thread {
@Override
public void run() {
Thread thread = new Thread();
thread.checkAccess();
System.out.println("Before setting thread name is : " + thread.getName());
// setName() sets the name of Thread
thread.setName("WebSparrow.org");
// getName() return the name of Thread
System.out.println("After setting thread name is : " + thread.getName());
}
public static void main(String[] args) throws SecurityException {
SetThreadNameExp threadName = new SetThreadNameExp();
threadName.start();
}
}
输出:
Before setting thread name is : Thread-1
After setting thread name is : WebSparrow.org
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/how-to-set-and-get-thread-name-in-java
内容来源于网络,如有侵权,请联系作者删除!