zoukankan      html  css  js  c++  java
  • 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管理等。

  • 相关阅读:
    django组件,有分页器(重要的很)
    wusir的django
    git 生成ssh key
    阶乘问题的题解
    拱猪计分的题解
    子数整数的题解
    安全逃离的题解
    题解 P1262 【间谍网络】
    斗地主的题解
    鸭王的题解
  • 原文地址:https://www.cnblogs.com/eason-d/p/9599675.html
Copyright © 2011-2022 走看看