Home > Articles

Basic Thread Operations in Java

  • Print
  • + Share This
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.

Listing 1: ThreadDemo3.java.

// ThreadDemo3.java

class MyThread extends Thread
{
  MyThread (String name)
  {
   setName (name);
  }

  public void run ()
  {
   System.out.println ("Name = " + getName ());

   for (int i = 0; i < 20; i++)
      System.out.println ("i = " + i);
  }
}

class ThreadDemo3 extends Thread
{
  public static void main (String [] args)
  {
   MyThread mt = new MyThread ("My Thread");
   mt.start ();

   for (int j = 0; j < 20; j++)
      System.out.println ("j = " + j);
  }
}

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():

MyThread (String name)
{
  super (name);
}
  • + Share This
  • 🔖 Save To Your Account