A casual investigation of the Thread class reveals an assortment of interesting methods for performing basic thread operations. This article by Java expert Jeff Friesen explores several of Thread's methods.

This article is excerpted from Java 2 By Example, Second Edition (Que, 2001), by Jeff Friesen.

This chapter is from the book

This chapter is from the book

A casual investigation of the Thread class reveals an assortment of
interesting methods for performing basic thread operations. Some of those
methods are deprecated (and should not be used). However, other methods are
quite useful and can simplify working with threads. This article explores
several of Thread's methods.

Thread Naming

All threads have names. By default, those names consist of the word
Thread followed by a hyphen character (-), followed by an
integer number starting at 0. You can introduce your own names by
working with the setName() and getName() methods. Those
methods make it possible to attach a name to a thread and retrieve a
thread's current name, respectively. That name can be useful for debugging
purposes.

The setName() method takes a String argument that
identifies a thread. Similarly, the getName() method returns that name
as a String. The ThreadDemo3 source code in Listing 1
demonstrates those methods.

ThreadDemo3's main() method creates a
MyThread object, and initializes that object by passing My
Thread to MyThread's constructor. In turn, that constructor
calls setName() to assign My Thread as the name of a
MyThread thread. Later, after the new thread has started, it prints out
that name in its run() method by first calling getName() to
retrieve that name.

Four of Thread's constructors support initializing
Thread objects with names. Those constructors include Thread(String
name) and Thread(Runnable target, String name). The following code
fragment initializes a MyThread object with a name by calling the
Thread(String name) constructor instead of by calling
setName():