Home » Java programming language

Java Thread Class String toString() method with Example

Java Thread Class String toString() method: Here, we are going to learn about the String toString() method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 29, 2019

Thread Class String toString()

  • This method is available in java.lang.Thread.toString().
  • This method is used to return the string representation of the thread including the thread name, thread priority, thread group.
  • This method returns a string representation of the thread that is easy to understand for end-user.
  • This method does not return an exception.

Syntax:

    String toString(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the Thread.

Return value:

The return type of this method is String, this method returns String representation of the thread.

Java program to demonstrate example of toString() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because 
    it is imported by default
*/

import java.lang.Thread;

class MyThread extends Thread {
    // Override run() method of Thread class
    public void run() {
        System.out.println("Thread Priority:" + Thread.currentThread().getPriority());
        System.out.println("Thread Name :" + Thread.currentThread().getName());
        System.out.println("Thread Group :" + Thread.currentThread().getThreadGroup());
    }
}

class Main {
    public static void main(String[] args) {
        // Creating an object of MyThread and calling start() of Thread class
        MyThread mt = new MyThread();
        mt.start();

        System.out.println("String representation of MyThread" + mt.toString());
    }
}

Output

E:\Programs>javac Main.java

E:\Programs>java Main
String representation of MyThreadThread[Thread-0,5,main]
Thread Priority:5
Thread Name :Thread-0
Thread Group :java.lang.ThreadGroup[name=main,maxpri=10]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.