2

In Java, is it always true that if thread1.getId() == thread2.getId(), then thread1.equals(thread2)?

I'm trying to track down a bug in a multithreaded application, and I noticed that it compares threads using Thread.equals() instead of comparing their IDs. The Thread class doesn't override its equals method, so the only way for two Thread objects to be equal is if they have the same memory address.

Edit:

So far I see two reasons why the answer might be no.

  1. thread1 might have been terminated, and thread2 might be reusing the same ID. Therefore the ids are equal but the threads are not.
  2. thread1 and thread2 are references to the same thread, but they're not the same object. (Not sure if this is possible.)
4

3 回答 3

4

获取ID

返回此线程的标识符。线程 ID 是创建此线程时生成的正长整数。线程 ID 是唯一的,并且在其生命周期内保持不变。当一个线程被终止时,这个线程 ID 可以被重用。

那是来自JavaThread文档。所以你的问题的答案是否定的,因为只要第一个线程被终止,另一个线程就可以具有与前一个线程相同的 ID

于 2013-08-01T15:42:05.777 回答
0

是的。正如 Thread 的 javadoc 所说:

    /**
 * Returns the identifier of this Thread.  The thread ID is a positive
 * <tt>long</tt> number generated when this thread was created.
 * The thread ID is unique and remains unchanged during its lifetime.
 * When a thread is terminated, this thread ID may be reused.
 *
 * @return this thread's ID.
 * @since 1.5
 */
public long getId() {
    return tid;
}
于 2013-08-01T15:39:07.797 回答
0

创建线程时,它们的标识符按顺序递增。它们每次都从 0 开始,并为创建它们的每个进程递增 1。因此,ID 不是全局唯一的。

于 2013-08-01T15:52:34.850 回答