当我处理 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();
}
请帮帮我。提前致谢。
最佳答案
此名称可从 native 代码访问,因此处理 char 数组比处理 Java 类型更容易。 core-lib-devs
邮件列表不久前讨论了这个问题,这里是来自线程的一封邮件的 link。最初的问题是 “相当多的时间用于 Thread.setName 调用,我认为其中很大一部分是进行新的字符分配和复制字符数组等”。引用部分答案:
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."
关于java - 为什么 Thread 类中的 setName 分配给字符数组?为什么不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10412408/