java中ThreadLocal

ThreadLocal可以为每个线程保存一份数据,相当与线程私有数据,不会被别的线程共享。
Thread.class

ThreadLocal.ThreadLocalMap threadLocals = null;  key为ThreadLocal实例,value要保存的数据

这样可以看得出来每个线程都会拥有一个单独的ThreadLocal.ThreadLocalMap(它是ThreadLocal一个静态内部类)
ThreadLocal.class

 //为当前线程写入值
 public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t); //每个线程都有一个ThreadLocalMap
    if (map != null)
        map.set(this, value);  //更新<ThreadLocal , value>
    else
        createMap(t, value);   //根据当前线程创建ThreadLocalMap
 }
 ThreadLocalMap getMap(Thread t) {
       return t.threadLocals;
 }
 void createMap(Thread t, T firstValue) {
      t.threadLocals = new ThreadLocalMap(this, firstValue);  //充分说明了每个线程都有独立的一个ThreadLocalMap
 }
 //根据当前线程获取值(真正获取值的时候是根据ThreadLocal实例来获取的)
 public T get() {
     Thread t = Thread.currentThread();
     ThreadLocalMap map = getMap(t);
     if (map != null) {
         ThreadLocalMap.Entry e = map.getEntry(this);
         if (e != null) {
             @SuppressWarnings("unchecked")
             T result = (T)e.value;
             return result;
         }
     }
     return setInitialValue();  //获取的时候发现当前线程没有ThreadMap就会初始化一个
  }
  private T setInitialValue() {
       T value = initialValue();
       Thread t = Thread.currentThread();
       //为什还要获取一遍判断一遍?感觉不用呀
       ThreadLocalMap map = getMap(t);
       if (map != null)
           map.set(this, value);
       else
           createMap(t, value);
       return value;
  }

每个线程都有一个ThreadMap<ThreadLocal,value>,这样Thread可以拥有多个ThreadLocal
还有那个疑问暂时不知道为什么?

附带一个例子:每个线程维持自己的一个数据库连接

public class ConnectionFactory {
    private static ThreadLocal<Connection> connections = new ThreadLocal<Connection>();
    private static String URL = "jdbc:mysql://127.0.0.1:3306/xia";
    private static String USER = "root";
    private static String PASSWORD = "123";
    public static Connection getConnectionInstance() {
        System.out.println(Thread.currentThread().getName() + "获取Connection");
        Connection conn = connections.get();
        if (conn != null) {
            return conn;
        }
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            connections.set(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}
public class ConnectionTest {
    public static void main(String[] args) {
        Connection conn_1 = ConnectionFactory .getConnectionInstance();
        Connection conn_2 = ConnectionFactory .getConnectionInstance();
        System.out.println(conn_1 == conn_2);
        new Thread(new Runnable() {
            Connection conn_3 = null;
            Connection conn_4 = null;

            @Override
            public void run() {
                conn_3 = ConnectionFactory .getConnectionInstance();
                conn_4 = ConnectionFactory .getConnectionInstance();
                System.out.println(conn_1 == conn_3);
                System.out.println(conn_3 == conn_4);
            }
        }).start();
    }
}

运行结果:

main获取Connection
Thu Jun 02 14:53:30 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
main获取Connection
true
Thread-0获取Connection
Thu Jun 02 14:53:30 CST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Thread-0获取Connection
false
true
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xia744510124/article/details/51564888
文章标签: java 线程 Thread Local
个人分类: java基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

java中ThreadLocal

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭