除非您这样做,否则ThreadLocal和ThreadPool不会相互交互.
您可以做的是一个ThreadLocal,它存储您要保留的所有状态,并在任务完成时重置该状态.您可以覆盖ThreadPoolExecutor.afterExecute(或beforeExecute)以清除ThreadLocal(s)
来自ThreadPoolExecutor
/**
* Method invoked upon completion of execution of the given Runnable.
* This method is invoked by the thread that executed the task. If
* non-null, the Throwable is the uncaught {@code RuntimeException}
* or {@code Error} that caused execution to terminate abruptly.
*
*
This implementation does nothing, but may be customized in
* subclasses. Note: To properly nest multiple overridings, subclasses
* should generally invoke {@code super.afterExecute} at the
* beginning of this method.
*
... some deleted ...
*
* @param r the runnable that has completed
* @param t the exception that caused termination, or null if
* execution completed normally
*/
protected void afterExecute(Runnable r, Throwable t) { }
您可以立即清除所有ThreadLocals,而不是跟踪所有ThreadLocals.
protected void afterExecute(Runnable r, Throwable t) {
// you need to set this field via reflection.
Thread.currentThread().threadLocals = null;
}