24

Is there a way to set a friendly name to a thread in code?

For example, I want the thread with name Thread-11 on the image was named something like 'MyImportThread'.

example-threads

4

6 回答 6

38

您可以轻松地在 Its Constructor中传递线程名称,例如:

Thread foo = new Thread("Foo");

...或通过调用Thread#setName

public final void setName (String threadName)

设置线程的名称。

作为thread.setName("Thread-11");或喜欢Thread.currentThread().setName("Thread-11");

于 2012-07-12T17:58:33.667 回答
8

检查Thread构造函数,有几个带String name参数的。或者您可以调用setName(String)现有线程。

于 2012-07-12T17:56:23.050 回答
6

你尝试过这样的事情吗?

Thread.currentThread().setName("MyThread");

Threads reference特别关注构造函数。

于 2012-07-12T17:56:23.097 回答
3

Thread有一个方法:

public final void setName (String threadName)

Since: API Level 1
Sets the name of the Thread.

你试过了吗?

于 2012-07-12T17:56:07.430 回答
3

尝试这个:

Thread thread = new Thread("MyImportThread") {
      public void run(){    
        // code
      }
   };
   thread.start();
   System.out.println(thread.getName());
于 2012-07-12T17:59:22.080 回答
1

是的,您可以使用以下方法为线程设置名称:

Thread.getCurrentThread().setName(threadName);
于 2012-07-12T17:58:52.470 回答