ThreadLoacl 小记

参考地址: https://www.cnblogs.com/dolphin0520/p/3920407.html

ThreadLoacl 本地线程变量

    为线程创建一个副本, 一个内部类ThreadLoaclMap
    每个线程有自己的ThreadLocal 并作为ThreadLoaclMap的键
    使用前必须先set 在get

package mall.test;

/**
 * ThreadLocal 
 *         为线程创建一个副本, 一个内部类ThreadLoaclMap
 *         每个线程有自己的ThreadLocal 并作为ThreadLoaclMap的键
 *         使用前必须先set 在get
 * @author guo
 *
 */
public class School {

    private static School school;
    private static ThreadLocal<School> threadLocal = new ThreadLocal<School>();
    
    private School(){
    }
    
    public static School instance() {
        School s = threadLocal.get();
        if(s == null) {
            school = new School();
            threadLocal.set(school);
        }
        return threadLocal.get();
    }
    
    public static void print(){
        System.out.println(Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //打印出main
        School.instance().print();
        
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                //打印出Thread-0
                School.instance().print();
            }
        });
        t.start();
    }

}

常用的使用场景为 用来解决 数据库连接、Session管理等。

原文地址:https://www.cnblogs.com/eason-d/p/9599675.html