简体   繁体   English

返回线程对象上的getId()类型

[英]Return type of getId() on a thread object

Why does, for example, Thread.currentThread().getId() return a long? 为什么,例如, Thread.currentThread().getId()返回一个long?

Does this really need to be 64 bits? 这真的需要64位吗? Like I'm going to ever have a machine running that number of threads! 就像我将要有一台机器运行那么多线程!

Seriously, it's a bit of a pain since I'm writing something that keeps a track of thread identifiers along with other bits and I'd really rather not have to use such a long number, else the unique key I have to generate is enormous. 说真的,这是一个痛苦,因为我正在写一些跟踪线程标识符以及其他位的东西,我真的不必使用这么长的数字,否则我必须生成的唯一密钥是巨大的。

Perhaps there is a convention on the long return; 也许有一个长期回归的公约; like the first 48 bits are always zero. 像前48位总是零。 I had a dig about on the internet but didn't find anything. 我在互联网上挖掘但没有发现任何东西。 I hope so; 希望如此; does anyone know for sure? 有人有确切消息么?

Thanks. 谢谢。

This code: 这段代码:

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

should give insight as to why. 应该提供有关原因的见解。 Essentially thread ids are assigned by a running counter, so if you don't terminate your JVM for a significant amount of time, this number would go above the long. 基本上线程ID是由一个运行的计数器分配的,所以如果你没有在很长一段时间内终止你的JVM,这个数字就会超过long。 I can only imagine that they did it to reduce the chance for collisions in long running threads. 我只能想象他们这样做是为了减少长时间运行线程中发生冲突的可能性。

Java applications are sand-boxed relative to other Java applications, which is way thread ID's are even likely to collide. Java应用程序相对于其他Java应用程序是沙盒子,这是线程ID甚至可能发生冲突的方式。

Threads are not meant to be unique across all application, they are only unique per application. 线程并非在所有应用程序中都是唯一的,它们仅对每个应用程序是唯一的。 Looking at the Thread.init method in the source, you can find: 查看源代码中的Thread.init方法,您可以找到:

private static synchronized long nextThreadID() {
    return ++threadSeqNumber;
}

/* For generating thread ID */
private static long threadSeqNumber;

I guess it's used to prevent a potential overflow bug. 我想它用于防止潜在的溢出错误。 As threads get created, the number would eventually overflow. 随着线程的创建,数字最终会溢出。 Long is just being 很长的只是存在

9223372036854775807(Max long value) - 2147483647(Max int value) = 9.223372e+18

a bit more safe:) 更安全:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM