- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个关于 java 和并发的问题。
假设我有一个名为“a”的 ThreadLocal 变量。我使用 CachedThreadPool 来获取新线程。当线程被重用时,ThreadLocal 变量 'a' 会发生什么变化?它保持相同的值(因为它是同一个线程)还是它开始为空(就像线程是新的一样)?
最佳答案
默认情况下,ThreadLocals 与线程一起重用。如果您需要重新初始化它们,您可以通过覆盖下面提到的方法来实现:
from javadoc for java.util.concurrent.ThreadPoolExecutor
Hook methods This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.
关于Java缓存线程池和线程本地,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7403809/
我是一名优秀的程序员,十分优秀!