为什么下面代码的输出是 Thread[main,5,main]

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);
    }
}

为什么上面代码的输出是 - Thread[main,5,main] ? 请解释

因为:

/**
 * 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() + "," +
                        "" + "]";
    }
}

Returns a string representation of this thread, including the thread's name, priority, and thread group.

来源:https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#toString()

因为thread.toString() returns这个线程的字符串表示,包括线程的名称、优先级和线程组。

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.

我们可以通过以下方式找到定义:

    @FastNative
    public static native Thread currentThread();
    

不需要检查native方法,只需要注意return类型是Thread,所以检查Thread中的Thread.toString定义。

AndroidSDK有源码

    /**
     * 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() + "," +
                            "" + "]";
        }
    }