有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java线程ID会在整个堆栈中保持不变吗?

如果我调用Thread.currentThread().getId(),我会得到一个表示当前线程ID的long

我正在编写的SessionContext类中使用用户threadId映射的线程ID。当用户对后端进行API调用时,我会根据用户ID存储当前的threadId,以便随时调用SessionContext。getUserId(),它将使用threadId将我映射回用户。但是,如果Thread.currentThread().getId()的结果在堆栈中的任何一点发生变化,这种方法将不起作用

我的问题是,这个ID会在整个堆栈中保持不变吗


共 (1) 个答案

  1. # 1 楼答案

    The documentation对此非常清楚:

    Returns the identifier of this Thread. The thread ID is a positive long 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.

    我认为这就是身份证的全部意义——它在它的一生中保持不变