'Why the out put of below code is Thread[main,5,main]
public class test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = Thread.currentThread();
System.out.println(t);
}
}
Why the output of above code is - Thread[main,5,main] ? Please Explain
Solution 1:[1]
Because thread.toString() returns a string representation of this thread, including the thread's name, priority, and thread group.
Solution 2:[2]
Returns a string representation of this thread, including the thread's name, priority, and thread group.
Source: https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#toString()
Solution 3:[3]
Because of:
/**
* Returns a string representation of this thread, including the
* thread's name, priority, and thread group.
*
* @return a string representation of this thread.
*/
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
return "Thread[" + getName() + "," + getPriority() + "," +
group.getName() + "]";
} else {
return "Thread[" + getName() + "," + getPriority() + "," +
"" + "]";
}
}
Solution 4:[4]
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#toString()
public String toString()
Returns a string representation of this thread, including the thread's name, priority, and thread group.
Here is how we can find the definition:
@FastNative
public static native Thread currentThread();
There is no need to check the native method, just notice that the return type is Thread, so check the Thread.toString definition in Thread.
Android SDK has the source code.
/**
* Returns a string representation of this thread, including the
* thread's name, priority, and thread group.
*
* @return a string representation of this thread.
*/
public String toString() {
ThreadGroup group = getThreadGroup();
if (group != null) {
return "Thread[" + getName() + "," + getPriority() + "," +
group.getName() + "]";
} else {
return "Thread[" + getName() + "," + getPriority() + "," +
"" + "]";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shree Krishna |
| Solution 2 | AdrianS |
| Solution 3 | gmaslowski |
| Solution 4 | Francis Bacon |

