Get Current Thread Name And ID in Java

In this post we’ll see how to set the thread name while creating a thread in Java, how to get the name of the current thread and how to get thread ID in Java.

Setting thread name in Java

For setting thread name in Java you can pass the thread name in the constructor or set it later using setName() method.

If you have a runnable task then you can use the following constructor-

  • public Thread(Runnable target, String name) – In this constructor for allocating a new Thread object, name is the name of the new thread.

Another constructor which can be used if you are extending the Thread class is this-

  • Thread(String name)– Here name argument is the name of the new thread.

Another option is to use setName() method

  • setName(String name)– Changes the name of this thread to be equal to the argument name.

Getting currently executing thread name in Java

For getting the name of the thread which is currently executing you need to call the getName() method on the currently executing thread.

So getting thread name in Java is a combination of these two methods.

  • currentThread()– Returns a reference to the currently executing thread object. It is a static method.
  • getName()– Returns this thread’s name.

For example-

Getting thread ID in Java

Another way to uniquely identify a thread in Java is by thread’s ID. To get the ID you can use the getId() method which is called on the currently executing thread.

  • getId()– Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.

Setting and getting thread name and Thread ID Java example

In the example three threads are created, for two of them thread name is passed as an argument in the constructor where as for one of them thread name is set using setName() method.

Later in the run method of the Runnable thread name and thread ID for the currently executing thread is displayed.

Output

That’s all for the topic Get Current Thread Name And ID in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

  • Race Condition in Java
  • AtomicInteger in Java With Examples
  • How to Convert String to double in Java
  • Methods in Java
  • instanceof Operator in Java
  • Word Count Program Using MapReduce in Hadoop
  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.