多线程系列--ThreadLocal

使用场景

参考网址:ThreadLocal作用、场景、原理 - 简书

数据库连接

public Connection initialValue() {
    return DriverManager.getConnection(DB_URL);
}

public static Connection getConnection() {  
    return connectionHolder.get();
}

Session管理

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;
}

多线程

public class Demo {
    static ThreadLocal localVariable = new ThreadLocal<>();

    static void print(String str){
        System.out.println(str + ":" + localVariable.get());
    }

    public static void main(String[] args) {
        Thread threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                localVariable.set("thread local variable");
                print("threadOne");
                System.out.println("threadOne remove after" + ":" + localVariable.get());
            }
        });

        Thread threadTwo = new Thread(new Runnable() {
            @Override
            public void run() {
                localVariable.set("thread local variable");
                print("threadTwo");
                System.out.println("threadTwo remove after" + ":" + localVariable.get());
            }
        });

        threadOne.start();
        threadTwo.start();
    }
}

运行结果:

threadTwo:thread local variable
threadTwo remove after:thread local variable
threadOne:thread local variable
threadOne remove after:thread local variable

实现原理

见:《Java并发编程之美》=> 1.11.2 ThreadLocal 的实现原理

你可能感兴趣的:(Java多线程)