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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值