gpt4 book ai didi

Java 线程概念 : Output Explanation

转载 作者:行者123 更新时间:2023-11-29 06:07:34 24 4
gpt4 key购买 nike

谁能告诉我为什么在运行程序时下一行显示 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(可能还有你的)上,5Thread.NORM_PRIORITY 的值.

关于Java 线程概念 : Output Explanation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8064024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com