Java Thread getId() 线程安全吗? [英] Is Java Thread getId() thread-safe?

查看:75
本文介绍了Java Thread getId() 线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题标题所说,Thread.getId() 线程安全吗?我最近在处理多线程时遇到了一个问题,解决方案是删除 getId() 调用,因为它使线程挂起.

As the question title says, is Thread.getId() thread-safe? I recently had a problem whilst multithreading and the solution was to remove the getId() call as it was making the thread hang.

推荐答案

是的,它是完全线程安全的.JDK8 中的完整实现是:

Yes, it's entirely thread-safe. The full implementation in JDK8 is:

public long getId() {
    return tid;
}

tidThread 对象的构造过程中被初始化一次,之后就不会改变.

tid is initialized once during construction of the Thread object and never changed afterward.

如果您的代码中有问题解决了删除它的问题,那是您在拥有 ID 后对 ID 所做的,而不是获取 ID.

If there was a problem in your code that removing it solved, it was what you were doing with the ID once you had it, not getting the ID.

这篇关于Java Thread getId() 线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆