java – 为什么Thread类中的setName分配给一个字符数组?为什么不是一个字符串?

前端之家收集整理的这篇文章主要介绍了java – 为什么Thread类中的setName分配给一个字符数组?为什么不是一个字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我在 Java中处理线程概念时,我已经看到了Thread.java源文件.我注意到setName()方法将字符串分配给名为“name []”的字符数组. Java具有String数据类型的特性,那么它们为什么使用字符数组.

在源文件中,它初始化为,

private char name[]; // why not "private String name;"

在setName()方法中,

public final void setName(String name) {
    checkAccess();
    this.name = name.tocharArray();
    }

请帮我.提前致谢.

解决方法

名称是从本机代码访问的,因此与使用Java类型的mangle相比,它更容易处理char数组. core-lib-devs邮件列表不久前讨论过这个问题,这是一个来自该主题link到一封邮件.最初的问题表明“相当多的时间进入Thread.setName调用,我认为其中很大一部分是进行新的char分配和复制char数组等”.引用答案:

There was an RFE for this way back in late 2002:

4745629 (thread) Thread.setName does needless string allocations
(don’t use char[])

The initial eval in 2002 stated:

“I can’t imagine that this serIoUsly impacts the performance of any
real program. Furthermore,changing the fields in Thread is
problematic due to the close relationship of this class with the VM.
That said,it might be worth addressing this in the context of some
Thread code-cleanup.”

Then in 2005 it was closed as “will not fix”:

“There are dependencies on the name representation being a char array in the JVM and this RFE must be respectfully rejected.”

原文链接:https://www.f2er.com/java/125110.html

猜你在找的Java相关文章