---
title: " JDK的ThreadLocal理解（三）优雅的使用ThreadLoca "
author: "aty"
date: "2013-08-11T17:05:58Z"
tags: []
categories: ["编程语言"]
slug: "jdk-threadlocal-threadloca"
draft: false
lastmod: "2013-08-11T17:05:58Z"
id: 1923131
url: "https://aty.iteye.com/blog/1923131"
---

ThreadLocal的使用可以参考struts2的ActionContext，个人觉得这种使用方式是比较优雅的：

1、ThreadLocal是业务无关的对象，对于开发代码来说，越少使用越好。

     这样能够尽可能的减少技术细节分散开发者对业务逻辑的关注

 

```
public class ActionContext implements Serializable 
{
    static ThreadLocal<ActionContext> actionContext = new  ThreadLocal<ActionContext>();

   /**
     * Sets the action context for the current thread.
     *
     * @param context the action context.
     */
    public static void setContext(ActionContext context) {
        actionContext.set(context);
    }

    /**
     * Returns the ActionContext specific to the current thread.
     *
     * @return the ActionContext for the current thread, is never <tt>null</tt>.
     */
    public static ActionContext getContext() {
        return actionContext.get();
    }
}
```

 经过这种封装后，整个ActionContext类，只有3个地方会涉及ThreadLocal的使用：变量定义、set、get。这3处使用都很简单，不容易出错