在Java 1.4中,获取线程ID是否有比使用Thread.getName()
更好的方法?
我的意思是,在单元测试中,getName()
返回类似于"Thread-1"
的内容,但在WebLogic 10中,我会得到"[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml"
。
在Java 1.4中,获取线程ID是否有比使用Thread.getName()
更好的方法?
我的意思是,在单元测试中,getName()
返回类似于"Thread-1"
的内容,但在WebLogic 10中,我会得到"[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'.xml"
。
Thread.getId(理论上可能会溢出,但在定义中不会并且实际上也不会发生)。
1.5版本目前已经进入其服务生命周期结束阶段,但如果您正在使用旧版本的1.4,则可以使用ThreadLocal
来实现自己的版本。(注意,不要过于严格遵循Java SE 6 API文档!)
如在“Thread.getId()全局唯一性问题”中提到的,并通过Thread.java源代码确认:
/* For generating thread ID */
private static long threadSeqNumber;
/* Set thread ID */
tid = nextThreadID();
private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}
如果你还在使用Java1.4,那么实现线程ID非常简单。
然而,这种实现意味着当你多次运行程序时,给定的线程将不会拥有相同的ID。
因此,根据你的需要,你可能需要实现一个命名策略,该策略同时具备以下特点: