- Tech Tutorials
- Friday, January 1, 2021
- Setting And Getting Thread Name And Thread ID in Java
- Setting Thread’s name in Java
- Thread ID in Java
- Setting thread name using constructor of the Thread class
- Setting thread name using setName() method Java example
- Getting thread name in java
- How to correctly get thread name in java?
- Method 1: Using Thread.currentThread().getName()
- Method 2: Using Thread.currentThread().toString()
- Method 3: Using a NamedThreadFactory
Tech Tutorials
Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.
Friday, January 1, 2021
Setting And Getting Thread Name And Thread ID in Java
In a multi-threading application if lots of thread have been spawned and you want to identify those thread then you can get the thread’s name or thread’s ID. This post shows how to set and get thread’s name in Java and how to get thread ID in Java.
Setting Thread’s name in Java
Thread ID in Java
Another way to uniquely identify a thread is to get thread’s ID in Java. Thread class has getId() method which returns the thread’s ID.
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 thread name using constructor of the Thread class
Thread class has a constructor Thread(Runnable target, String name) which takes two arguments, a runnable object and a String which sets the thread’s name.
class MyThread implements Runnable < @Override public void run() < // Getting thread's name System.out.println("Thread Name- " +Thread.currentThread().getName()); // Getting thread's ID System.out.println("Thread ID- " +Thread.currentThread().getId() + " For " + Thread.currentThread().getName()); try < Thread.sleep(10); >catch (InterruptedException e) < e.printStackTrace(); >System.out.println("Finished with thread"); > > public class ThreadName < public static void main(String[] args) < // Creating 3 threads Thread t1 = new Thread(new MyThread(), "Thread-1"); Thread t2 = new Thread(new MyThread(), "Thread-2"); Thread t3 = new Thread(new MyThread(), "Thread-3"); // Starting threads t1.start(); t2.start(); t3.start(); >>
Thread Name- Thread-2 Thread Name- Thread-3 Thread Name- Thread-1 Thread ID- 12 For Thread-3 Thread ID- 11 For Thread-2 Thread ID- 10 For Thread-1 Finished with thread Finished with thread Finished with thread
Here it can be seen that thread’s name is set in the constructor and thread’s ID is also retrieved.
Setting thread name using setName() method Java example
class MyThread implements Runnable < @Override public void run() < // Getting thread's name System.out.println("Thread Name- " +Thread.currentThread().getName()); // Getting thread's ID System.out.println("Thread ID- " +Thread.currentThread().getId() + " For " + Thread.currentThread().getName()); try < Thread.sleep(10); >catch (InterruptedException e) < e.printStackTrace(); >System.out.println("Finished with thread"); > > public class ThreadName < public static void main(String[] args) < // Creating 3 threads Thread t1 = new Thread(new MyThread()); t1.setName("Thread-1"); Thread t2 = new Thread(new MyThread()); t2.setName("Thread-2"); Thread t3 = new Thread(new MyThread()); t3.setName("Thread-3"); // Starting threads t1.start(); t2.start(); t3.start(); >>
Thread Name- Thread-1 Thread Name- Thread-3 Thread Name- Thread-2 Thread ID- 12 For Thread-3 Thread ID- 10 For Thread-1 Thread ID- 11 For Thread-2 Finished with thread Finished with thread Finished with thread
That’s all for this topic Setting And Getting Thread Name And Thread ID in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Getting thread name in java
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java
How to correctly get thread name in java?
When working with multi-threaded programming in Java, it is often necessary to identify a specific thread by its name. This is useful for debugging and logging purposes, as well as for determining which thread is executing a particular block of code. However, there are a few different ways to get the name of a thread in Java, and it is important to understand the differences between them in order to get the correct name for the desired thread.
Method 1: Using Thread.currentThread().getName()
To get the name of the current thread in Java, you can use the Thread.currentThread().getName() method. This method returns a String representing the name of the currently executing thread.
Here’s an example of how to use Thread.currentThread().getName() :
public class MyThread implements Runnable public void run() System.out.println("Current thread name: " + Thread.currentThread().getName()); > public static void main(String[] args) Thread thread = new Thread(new MyThread()); thread.start(); > >
In this example, we create a new thread by passing an instance of MyThread to the Thread constructor. When the thread is started, the run() method is executed, which calls Thread.currentThread().getName() to get the name of the currently executing thread.
Another example of using Thread.currentThread().getName() :
public class MyTask implements CallableString> public String call() throws Exception return "Task executed by thread: " + Thread.currentThread().getName(); > public static void main(String[] args) throws Exception ExecutorService executor = Executors.newSingleThreadExecutor(); FutureString> result = executor.submit(new MyTask()); System.out.println(result.get()); executor.shutdown(); > >
In this example, we create a Callable task by implementing the call() method. When the task is executed by an ExecutorService , we use Thread.currentThread().getName() to get the name of the thread executing the task.
Overall, Thread.currentThread().getName() is a simple and effective way to get the name of the currently executing thread in Java.
Method 2: Using Thread.currentThread().toString()
To get the name of a thread in Java, you can use the Thread.currentThread().toString() method. This method returns a string representation of the current thread, which includes its name.
Here is an example code snippet that demonstrates how to use this method:
public class ThreadExample implements Runnable public void run() System.out.println("Current thread name: " + Thread.currentThread().toString()); > public static void main(String[] args) Thread t1 = new Thread(new ThreadExample()); t1.setName("MyThread"); t1.start(); > >
In this example, we create a new thread t1 and set its name to «MyThread» . We then start the thread and it executes the run() method, which uses Thread.currentThread().toString() to print the current thread’s name to the console.
Current thread name: Thread[MyThread,5,main]
The string returned by Thread.currentThread().toString() includes the thread’s name ( MyThread ), its priority ( 5 ), and the name of the thread group it belongs to ( main ).
In summary, to get the name of a thread in Java using Thread.currentThread().toString() , you can follow these steps:
- Call Thread.currentThread() to get the current thread.
- Call toString() on the current thread to get a string representation of the thread.
- Extract the thread name from the string representation.
Note that the name of a thread can also be set using the setName() method, as shown in the example above.
Method 3: Using a NamedThreadFactory
To get the thread name in Java, you can use a NamedThreadFactory. This is a convenient way to create threads with a specific name, making it easier to identify them in logs and debugging.
Here’s an example of how to use a NamedThreadFactory to get the thread name:
import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; public class Example public static void main(String[] args) ThreadFactory factory = Executors.defaultThreadFactory(); Thread thread = factory.newThread(new MyRunnable()); thread.start(); > > class MyRunnable implements Runnable @Override public void run() String threadName = Thread.currentThread().getName(); System.out.println("Thread name: " + threadName); > >
In this example, we create a new thread using the default thread factory, which is a NamedThreadFactory. We then start the thread, which executes the run() method of the MyRunnable class. Inside the run() method, we use the getName() method of the current thread to get its name and print it to the console.
Here’s another example that shows how to create a custom NamedThreadFactory:
import java.util.concurrent.ThreadFactory; public class CustomThreadFactory implements ThreadFactory private final String namePrefix; public CustomThreadFactory(String namePrefix) this.namePrefix = namePrefix; > @Override public Thread newThread(Runnable r) Thread t = new Thread(r); t.setName(namePrefix + "-" + t.getId()); return t; > >
In this example, we create a custom thread factory that adds a prefix to the thread name. We pass the prefix as a parameter to the constructor, and use it to create a new thread with a name that includes the prefix and the thread ID. We then return the new thread to be used by the executor.
To use the custom thread factory, we can modify the previous example like this:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Example public static void main(String[] args) ThreadFactory factory = new CustomThreadFactory("MyThread"); ExecutorService executor = Executors.newSingleThreadExecutor(factory); executor.execute(new MyRunnable()); executor.shutdown(); > >
In this example, we create a new custom thread factory with the prefix «MyThread». We then create a new single-threaded executor and pass the custom thread factory to it. We use the executor to execute the MyRunnable class, which gets the thread name as before.
Overall, using a NamedThreadFactory is a simple and effective way to get the thread name in Java. By creating threads with specific names, you can make debugging and troubleshooting much easier.