gpt4 book ai didi

java - 是否可以从不同的类访问 java 变量但对不同的线程不可见?

转载 作者:行者123 更新时间:2023-11-30 06:46:41 25 4
gpt4 key购买 nike

据我了解,静态变量在 JAVA 中的所有线程中都是可见/可访问的。

有没有办法定义一个只能由其线程内的类访问的变量?

最佳答案

如果我正确理解你的意图,那么是的,可以通过ThreadLocal: https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

关于java - 是否可以从不同的类访问 java 变量但对不同的线程不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47221728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com