小言_互联网的博客

ThreadLocal实现线程单例

308人阅读  评论(0)

提示:其实是伪线程安全的。
使用场景: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糖果罐
扫码关注

转载:https://blog.csdn.net/dataiyangu/article/details/104119875
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场