谁能告诉我为什么在运行程序时下一行显示 5
CURRENT THREAD IS: Thread[main,5,main]
该程序来自 Java Complete Reference 一书,程序如下:
public class CurrentThreadDemo
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("CURRENT THREAD IS: " + t);
t.setName("ChangedThreadName");
System.out.println("CHANGED THREAD NAME IS: " + t);
try
{
for(int n = 8; n > 0; n--)
System.out.println(n);
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted " + e);
}
}
}
以下程序的输出是:
CURRENT THREAD IS: Thread[main,5,main]
CHANGED THREAD NAME IS: Thread[ChangedThreadName,5,main]
8
7
6
5
4
3
2
1
最佳答案
您正在隐式调用 Thread.toString()
.该方法的 Javadoc 指出它
returns a string representation of this thread, including the thread's name, priority, and thread group.
查看源代码证实了这一点:
return "Thread[" + getName() + "," + getPriority() + "," +
group.getName() + "]";
综上所述,第二项是线程优先级。
在我的 JDK(可能还有你的)上,5
是 Thread.NORM_PRIORITY
的值.
关于Java 线程概念 : Output Explanation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8064024/