Java线程getId()线程安全吗?
答
是的,它完全是线程安全的。在JDK8全面推行是:
public long getId() {
return tid;
}
tid
的建造Thread
对象的过程中初始化一次,从来没有改变之后。
如果您的代码中存在问题,请将其解除,这就是您一旦拥有了并且使用ID为而没有获取ID。
答
简短的回答:是的,
长回答:线程安全手段防范竞争条件
/**
* 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;
}
正如你看到的方法是不同步的,而tid
是私有的,而不是最后宣布,但是tid
在私有方法init
中设置,并且在此之后永远不会更改,这使得tid
的值不可变,从而使其成为线程安全的
因此,首先你回答否,然后删除它,一旦我发布你改变你的答案是和撤消删除它。 –
是的,作为一个人能够正确地尽我所需/需要我的答案....感谢评论:) –
这将是一件好事,如果你在**发布之前做了尽职调查**而不是之后。 –