关闭

java中ThreadLocal

标签: java线程ThreadLocal
731人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:66132次
    • 积分:1763
    • 等级:
    • 排名:千里之外
    • 原创:106篇
    • 转载:41篇
    • 译文:1篇
    • 评论:11条
    最新评论