线程范围内的线程共享(多线程)

首先介绍一下两个方法:数据库

1.经过Map进行实现spa

  主键为Thread ,value 为数据,线程

  主要思路为:与线程绑定,不一样的线程之间的数据相互独立 
blog

 

2.经过ThreadLocal 实现get

  首先先介绍一下ThreadLocal 的原理源码

  每一个Thread ,都有一个ThreadLocalMap ,因此每次经过ThreadLocal .get的时候,至关因而在当前线程的ThreadLocalMap  查查找 key为 ThreadLocal(调用者)的value值。it

这个是ThreadLocal  get方法的源码io

 

ThreadLocal的主要应用场景:ast

1.用来解决数据库链接、Session管理class

    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {  
        public Connection initialValue() {  
            return DriverManager.getConnection(DB_URL);  
        }  
    };  
      
    public static Connection getConnection() {  
        return connectionHolder.get();  
    }  

 

private static final ThreadLocal threadSession = new ThreadLocal();  
  
public static Session getSession() throws InfrastructureException {  
    Session s = (Session) threadSession.get();  
    try {  
        if (s == null) {  
            s = getSessionFactory().openSession();  
            threadSession.set(s);  
        }  
    } catch (HibernateException ex) {  
        throw new InfrastructureException(ex);  
    }  
    return s;  
}  

 2.第二个场景用于:

  线程多实例,须要保存分离每一个线程的数据

相关文章
相关标签/搜索