zoukankan      html  css  js  c++  java
  • 线程范围内的线程共享(多线程)

    首先介绍一下两个方法:

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

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

     

  • 相关阅读:
    没人关注的角落是个好地方
    PICKIT3 WIN10 无法连接问题解决
    TM1650+msp430单片机 调试及遇到问题的总结
    即将会来日常更新stm32的学习过程
    Learn Arduino the hard way 1——点亮一个LED
    准备再次开始更新
    Tcl之Read files for synthesis
    Verilog之event
    Tcl之Math
    Digital design之Boolean Algebra
  • 原文地址:https://www.cnblogs.com/lizhiyan-world/p/6884893.html
Copyright © 2011-2022 走看看