Thread Naming

The next topic we will examine concerns the thread support methods that are used mainly for thread “bookkeeping.” First, it is possible to assign a String name to the Thread object itself:

void setName(String name)

Assigns a name to the Thread instance.

String getName()

Gets the name of the Thread instance.

The Thread class provides a method that allows us to attach a name to the thread object and a method that allows us to retrieve the name. The system does not use this string for any specific purpose, though the name is printed out by the default implementation of the toString() method of the thread. The developer who assigns the name is free to use this string for any purpose desired. For example, let’s assign a name to our TimerThread class:

import java.awt.*;

public class TimerThread extends Thread {
    Component comp;                // Component that needs repainting
    int timediff;                  // Time between repaints of the component
    volatile boolean shouldRun;    // Set to false to stop thread

    public TimerThread(Component comp, int timediff) {
        this.comp = comp;
        this.timediff = timediff;
        shouldRun = true;
        setName("TimerThread(" + timediff + " milliseconds)");
    }

    public void run() {
        while (shouldRun) {
            try {
                comp.repaint();
                sleep(timediff);
            } catch (Exception e) {}
        }
    }
}

In this version of the TimerThread class, we assigned a name to the thread. The name that is assigned is simply “TimerThread” followed by the number of milliseconds used in this timer thread. If the getName() method is later ...

Get Java Threads, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.