gpt4 book ai didi

Java缓存线程池和线程本地

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:21 25 4
gpt4 key购买 nike

我有一个关于 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/

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