关于threadLocal

来源:互联网 发布:软件合同登记 编辑:程序博客网 时间:2024/05/16 08:23
Threadlocal原理最终归为的本源就是map一个hash的存储结构 key是线程,value是你定义的变量,实现线程的变量分离,保证线之间变量的独立性
例如,数据库连接池
public class DB {    private static DataSource ds;    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();    static {        ds = new ComboPooledDataSource();    }    //防止实例    private DB(){    }    public static DataSource getDataSource() {        return ds;    }    /***     * 从连接池获取conn连接     * @return     */    public static Connection getConnection() {        try {            // 得到当前线程上绑定的连接            Connection conn = threadLocal.get();            if (conn == null) { // 代表线程上没有绑定连接                conn = ds.getConnection();                threadLocal.set(conn);            }            return conn;        } catch (Exception e) {            throw new RuntimeException(e);        }    }    /***     * 开启事务     */    public static void beginTransaction() {        try {            // 得到当前线程上绑定连接开启事务            Connection conn = getConnection();            if(!conn.getAutoCommit()){                logger.warn(" connection got the last autoCommit value ! ");            }            conn.setAutoCommit(false);        } catch (Exception e) {            throw new RuntimeException(e);        }    }    /**     * 提交事务     */    public static void commitTransaction() {        try {            Connection conn = threadLocal.get();            if (conn != null) {                conn.commit();            }        } catch (Exception e) {            throw new RuntimeException(e);        }    }     /***     * 关闭连接     */    public static void closeConnection() {        try {            Connection conn = threadLocal.get();            if (conn != null) {                conn.close();            }        } catch (Exception e) {            throw new RuntimeException(e);        } finally {            threadLocal.remove();        }    }    /***     * 关闭连接     */    public static void rollback() {        try {            Connection conn = threadLocal.get();            if (conn != null) {                conn.rollback();;            }        } catch (Exception e) {            throw new RuntimeException(e);        }     }}








详解例子:
public class Test {public static ThreadLocal<Integer> thres=new ThreadLocal<Integer>() {@Overrideprotected Integer initialValue() {// TODO Auto-generated method stubint num=0;return num;}    }; public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {/* A a=new A();Field[] declaredFields = a.getClass().getDeclaredFields();for(Field field:declaredFields) {String name = field.getName();if(name.equals("SAMPLING_RATE")){System.out.println(field.get(null));}}*/Thread[] the=new Thread[5];for(Thread thread:the){thread=new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stub     int num=thres.get();     num=num+10;     System.out.println(num);}});thread.start();}}static class A {public static final String SAMPLING_RATE = "1000140";public static final String IRR_TYPE = "1000141";}}




运行结果
10
10
10
10
10


底层原理:
 
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;    }




initialValue可以理解为上面threadLocal中你定义的那个变量,你重写了initalValue方法。就是这样的。