Course contentsShow
← Java
Lesson 2566 of 2,87048. Concurrency FundamentalsFree lesson

Thread Naming and Identification

Learn to name threads, retrieve thread names, and use Thread.currentThread for identification.

Thread Naming and Identification

You'll learn how to give threads meaningful names and retrieve information about the current thread for debugging and monitoring.

Why Thread Names Matter

When you create multiple threads in an application, they're just faceless workers without names. Imagine a busy restaurant kitchen with five cooks—if the manager needs to communicate with them, calling out "Hey, you!" isn't very effective. Thread names serve the same purpose: they help you identify which thread is doing what, especially when debugging or logging.

Naming Threads

You can name a thread in two ways:

  1. At construction time using a Thread constructor that accepts a name:
Thread worker = new Thread(() -> {
    // task code
}, "Worker-1");
  1. After creation using setName:
Thread worker = new Thread(() -> {
    // task code
});
worker.setName("Background-Worker");

Retrieving Thread Information

Use getName() to retrieve a thread's name:

Thread t = new Thread(() -> {
    System.out.println("Running in: " + Thread.currentThread().getName());
}, "MyThread");
t.start();
// Output: Running in: MyThread

The Thread.currentThread() Method

Thread.currentThread() is your "who am I?" method. It returns a reference to the currently executing thread object. This is crucial when you need to identify or manipulate the thread from within its own execution:

Runnable task = () -> {
    Thread me = Thread.currentThread();
    System.out.println("Name: " + me.getName());
    System.out.println("ID: " + me.getId());
};

Every thread also has a unique numeric ID accessible via getId(), automatically assigned by the JVM.

Key Takeaway: Use meaningful thread names via constructors or setName(), and leverage Thread.currentThread() to identify the executing thread for logging, debugging, and runtime decisions.