Java 线程概念 : Output Explanation

标签 java multithreading

谁能告诉我为什么在运行程序时下一行显示 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/

相关文章:

java - Riak 2i - 更新删除二级索引

java - 在 Java 中使用 JButton 打开后窗口无法正确显示

multithreading - Azure 服务 TopicClient 线程安全且可重用吗?

java - ConcurrentModificationException - Memcached 设置并从多线程获取

java - 检索连接的组件 Graphstream

java - [JAVA]我将Integer类型的LinkedList转换为Array。转换后如何确定数组的大小

java - 解析有关搜索条件的用户输入

java - Runnable 或 Executor 服务

java - 图形 2d 对象的引用在孤立线程中不起作用

c - 用户级线程上下文切换 : How to detect when a thread is blocking in C?