Naming Threads

It's often useful to give different threads in the same class names so you can tell them apart. The following constructor allows you to do that:

public Thread(String name)
This is normally called from the constructor of a subclass, like this:

public class NamedBytePrinter extends Thread {

  public NamedBytePrinter(String name) {
    super(name);
  } 

  public void run() {
    for (int b = -128; b < 128; b++) {
      System.out.println(this.getName() + ": " + b);
    }
  
  }
  
}
The getName() method of the Thread class returns this value.

The following program now distinguishes the output of different threads:

public class NamedThreadsTest {

  public static void main(String[] args) {
  
    NamedBytePrinter frank = new NamedBytePrinter("Frank");
    NamedBytePrinter mary = new NamedBytePrinter("Mary");
    NamedBytePrinter chris = new NamedBytePrinter("Chris");
    frank.start();
    mary.start();
    chris.start();
  
  }

}

Previous | Next | Top
Last Modified July 11, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu