zoukankan      html  css  js  c++  java
  • ThreadLocal的学习

    本文摘自于:http://www.cnblogs.com/dolphin0520/p/3920407.html

    (1)ThreadContext<T>为基于键/值对的当前线程提供了一种绑定和非绑定对象的方法。

    这个类提供线程局部变量。这些变量与普通的变量不同,因为每个访问一个线程的线程(通过其get或set方法)都有自己的独立初始化变量的副本。

    ThreadLocal实例通常是希望将状态与线程关联的类中的私有静态字段(例如:一个用户ID或事务ID)。每个线程都对线程本地变量的副本有一个隐式引用,

    只要线程还活着,ThreadLocal实例就可以访问;在一个线程消失之后,所有线程本地实例的副本都将被垃圾收集(除非存在其他引用)。

    <T>为线程中保存的对象。即一个类T是线程的一个类属性。

    常用的方法有:

     1 public class ThreadLocal<T> {
     2 
     3 //设置属性
     4 
     5 public void set(T value) {
     6 Thread t = Thread.currentThread();
     7 ThreadLocalMap map = getMap(t);
     8 if (map != null)
     9 map.set(this, value);
    10 else
    11 createMap(t, value);
    12 }
    13 
    14 //获取属性
    15 
    16 public T get() {
    17 Thread t = Thread.currentThread();
    18 ThreadLocalMap map = getMap(t);
    19 if (map != null) {
    20 ThreadLocalMap.Entry e = map.getEntry(this);
    21 if (e != null)
    22 return (T)e.value;
    23 }
    24 return setInitialValue();
    25 }
    26 
    27 //获取线程的 ThreadLocal.ThreadLocalMap
    28 
    29 ThreadLocalMap getMap(Thread t) {
    30 return t.threadLocals;
    31 }
    32 
    33 }
    34 
    35 //新建一个线程本地的localMap
    36 
    37 void createMap(Thread t, T firstValue) {
    38 t.threadLocals = new ThreadLocalMap(this, firstValue);
    39 }

    (2)使用例子:连接、会话如下:

     1 private static ThreadLocal<Connection> connectionHolder
     2 = new ThreadLocal<Connection>() {
     3 public Connection initialValue() {
     4     return DriverManager.getConnection(DB_URL);
     5 }
     6 };
     7  
     8 public static Connection getConnection() {
     9 return connectionHolder.get();
    10 }
     1 private static final ThreadLocal threadSession = new ThreadLocal();
     2  
     3 public static Session getSession() throws InfrastructureException {
     4     Session s = (Session) threadSession.get();
     5     try {
     6         if (s == null) {
     7             s = getSessionFactory().openSession();
     8             threadSession.set(s);
     9         }
    10     } catch (HibernateException ex) {
    11         throw new InfrastructureException(ex);
    12     }
    13     return s;
    14 }

     

  • 相关阅读:
    ES6语法异步转同步(小程序中测试)
    js 图片保存至手机相册
    js字符串中查看有没有在数组中的值有的话全部替换掉
    java.sql.SQLException: Access denied for user 'Administrator'@'localhost'
    <mvc:annotation-driven>新增标签
    SpingMVC之<mvc:annotation-driven/>标签
    DecimalFormat 的用法
    sui.js和workflow2.js内容详解
    mac地址和ip地址、子网掩码和默认网关
    MQTT 3 ——MQTT与Spring Mvc整合
  • 原文地址:https://www.cnblogs.com/panql341/p/7169485.html
Copyright © 2011-2022 走看看