zoukankan      html  css  js  c++  java
  • ThreadLocal实现线程单例

    提示:其实是伪线程安全的。
    使用场景:ORM框架中实现多数据源动态切换。

    public class ThreadLocalSingleton {
        private static final ThreadLocal<ThreadLocalSingleton> threadLocalInstance =
                new ThreadLocal<ThreadLocalSingleton>(){
                    @Override
                    protected ThreadLocalSingleton initialValue() {
                        return new ThreadLocalSingleton();
                    }
                };
    
        private ThreadLocalSingleton(){}
    
        public static ThreadLocalSingleton getInstance(){
            return threadLocalInstance.get();
        }
    }
    
    public static void main(String[] args) { 
    	System.out.println(ThreadLocalSingleton.getInstance()); 
    	System.out.println(ThreadLocalSingleton.getInstance()); 
    	System.out.println(ThreadLocalSingleton.getInstance()); 
    	System.out.println(ThreadLocalSingleton.getInstance()); 
    	System.out.println(ThreadLocalSingleton.getInstance());
    	Thread t1 = new Thread(new ExectorThread()); 
    	Thread t2 = new Thread(new ExectorThread()); 
    	t1.start(); 
    	t2.start();
    	System.out.println("End"); 
    }
    

    结果:
    在这里插入图片描述
    mian线程,Thread-1线程,Thread-0线程,各自线程中是唯一的,但是各个线程之间是互不一样的。
    通过查看ThreadLocal的源码
    在这里插入图片描述
    ThreadLocalMap的set方法key其实就是当前的线程本身,value就是我们放到map中的value的值,所以就保证了上面出现的结果。即线程内是安全的。

    这里其实是注册式单利中的容器类

    Java糖果罐
    扫码关注
  • 相关阅读:
    【VirtualBox】共享文件夹失效问题
    【Ubuntu】全局代理
    phpStudy(lnmp)集成环境安装
    MemcacheQ 的安装与使用
    Windows 64位下安装Redis详细教程
    http与https的区别
    cookie 和session 的区别详解
    setcookie各个参数详解
    MySQL 数据备份与还原
    linux命令行下导出导入.sql文件
  • 原文地址:https://www.cnblogs.com/LeesinDong/p/12246633.html
Copyright © 2011-2022 走看看