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

首先介绍一下两个方法:

1.通过Map进行实现

  主键为Thread ,value 为数据,

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

2.通过ThreadLocal 实现

  首先先介绍一下ThreadLocal 的原理

  每个Thread ,都有一个ThreadLocalMap ,所以每次通过ThreadLocal .get的时候,相当于是在当前线程的ThreadLocalMap  查查找 key为 ThreadLocal(调用者)的value值。

这个是ThreadLocal  get方法的源码

ThreadLocal的主要应用场景:

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

    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.第二个场景用于:

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

 

原文地址:https://www.cnblogs.com/lizhiyan-world/p/6884893.html