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

Thread Names and setName()

Assign meaningful names to threads for easier debugging and logging.

Thread Names and setName()

You'll learn: How to assign meaningful, custom names to threads to make debugging and logging dramatically easier.


Why Thread Names Matter

By default, Java gives threads generic names like Thread-0, Thread-1, and so on. When you're debugging a multi-threaded application with logs or stack traces, seeing dozens of Thread-5 entries tells you almost nothing about what that thread was supposed to be doing.

Think of it like this: Imagine a busy restaurant kitchen where every chef is just called "Chef #1," "Chef #2," etc. When something goes wrong, it's hard to know whether the problem was with the pastry chef or the grill chef. Giving threads descriptive names is like giving each chef a proper role title—it makes communication and problem-solving much clearer.


Using setName() to Assign Thread Names

The Thread class provides a setName(String name) method that lets you assign a meaningful identifier:

Thread worker = new Thread(() -> {
    System.out.println("Processing data...");
});

worker.setName("DataProcessorThread");
worker.start();

You can also pass the name directly to the Thread constructor:

Thread worker = new Thread(() -> {
    System.out.println("Working...");
}, "DatabaseCleanupThread");

worker.start();

Inside a thread, you can retrieve its name using Thread.currentThread().getName():

Thread logger = new Thread(() -> {
    String name = Thread.currentThread().getName();
    System.out.println(name + " is logging events.");
}, "EventLogger");

logger.start();

Key Takeaway: Always give your threads descriptive names using setName() or the Thread constructor—it transforms confusing stack traces into readable diagnostics and makes debugging multi-threaded code far less painful.