3

有没有办法更改启动的名称ThreadThread.setName(String name)仅在线程初始化块中可用?

4

3 回答 3

8

该函数称为 setName(String name);

Thread t = new Thread(...);
t.start();
t.setName("...");
于 2012-06-02T18:48:56.873 回答
6

只要 SecurityManager 允许,您可以在代码中仍然引用原始线程的任何部分设置它。

于 2012-06-02T18:49:35.787 回答
0

可以在实例化 Thread 对象时设置 Thread 名称,也可以在事后使用Thread.currentThread().setName

public class NamedThreadExample implements Runnable {

  public static final String THREAD_NAME_GOES_HERE = "Original Name";
  public static final String NEW_THREAD_NAME_GOES_HERE = "New Name";

  public void run() {
    System.out.println("I am a Thread and my name is " 
                        + Thread.currentThread().getName());

    Thread.currentThread().setName(NEW_THREAD_NAME_GOES_HERE);

    System.out.println("I am a Thread and my name is " 
                        + Thread.currentThread().getName());
  }

  public static void main(String args[]) {
    (new Thread(new NamedThreadExample(), THREAD_NAME_GOES_HERE)).start();
  }
}

产生输出

I am a Thread and my name is Original Name
I am a Thread and my name is New Name

请参阅http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#Thread%28java.lang.Runnable,%20java.lang.String%29

于 2012-06-02T19:02:42.407 回答