Java Thread toString() Method



Description

The Java Thread toString() method returns a string representation of this thread, including the thread's name, priority, and thread group.

Declaration

Following is the declaration for java.lang.Thread.toString() method

public String toString()

Parameters

NA

Return Value

This method returns string representation of this thread.

Exception

Example: Getting String Representation in Multithreaded Environment

The following example shows the usage of Java Thread toString() method. In this program, we've created a thread class ThreadDemo by implementing Runnable interface. In constructor, a new thread is created using new Thread and started using start() method. In run() method, we're printing string representation of the thread. In main method, we're creating three threads of ThreadDemo class.

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   Thread t;

   ThreadDemo() {

      t = new Thread(this);
      // this will call run() function
      t.start();
   }

   public void run() {

      // returns a string representation of this thread 
      System.out.println(t.toString());
   }

   public static void main(String[] args) {
      new ThreadDemo();
	  new ThreadDemo();
	  new ThreadDemo();
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Thread[#22,Thread-1,5,main]
Thread[#23,Thread-2,5,main]
Thread[#21,Thread-0,5,main]

Example: Getting String Representation in Single Threaded Program

The following example shows the usage of Java Thread toString() method. In this program, we've created a class ThreadDemo. In main method, current thread is retrieved using currentThread() method and it is printed. Using toString(), the string representation of current thread is printed.

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
      
      // set thread priority to 1
      t.setPriority(1);
     
      // prints the current thread
      System.out.println("Thread = " + t.toString());
      
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Thread = Thread[#1,Admin Thread,1,main]
java_lang_thread.htm
Advertisements