java设计模式——ThreadLocal线程单例

1、定义一个ThreadLocal线程单例,代码如下:

package com.rf.designPatterns.singleton.threadLocalSingleton;

/**
 * @description: ThreadLocal线程单例,为每一个线程提供一个对象,在访问的时候相互不影响
 * @author: xiaozhi
 * @create: 2020-06-05 13:52
 */
public class ThreadLocalSingleton {

    //创建ThreadLocal实例对象,并且重写initialValue方法
    private static final ThreadLocal<ThreadLocalSingleton>  threadLocalSingleton =
            new ThreadLocal<ThreadLocalSingleton>(){
        @Override
        protected ThreadLocalSingleton initialValue() {
            return new ThreadLocalSingleton();
        }
    };

    //构造方法
    private ThreadLocalSingleton(){

    }

    //提供对外暴露的方法,获取ThreadLocalSingleton对象
    public static ThreadLocalSingleton getInstance(){
        return threadLocalSingleton.get();
    }
}

2、定义一个多线程类,代码如下:

package com.rf.designPatterns.singleton.threadLocalSingleton;

/**
 * @description:
 * @author: xiaozhi
 * @create: 2020-06-05 14:01
 */
public class MyThread implements Runnable{

    @Override
    public void run() {
        ThreadLocalSingleton instance = ThreadLocalSingleton.getInstance();
        System.out.println(Thread.currentThread().getName()+":"+instance);
    }
}

3、定义一个测试类,代码如下:

package com.rf.designPatterns.singleton.threadLocalSingleton;

/**
 * @description:
 * @author: xiaozhi
 * @create: 2020-06-05 14:02
 */
public class ThreadLocalSingletonTest {
    public static void main(String[] args) {
        System.out.println("main thread :"+ThreadLocalSingleton.getInstance());
        System.out.println("main thread :"+ThreadLocalSingleton.getInstance());
        System.out.println("main thread :"+ThreadLocalSingleton.getInstance());

        Thread thread1 = new Thread(new MyThread());
        Thread thread2= new Thread(new MyThread());
        thread1.start();
        thread2.start();
    }
}

4、输出结果,如下图:
java设计模式——ThreadLocal线程单例_第1张图片

你可能感兴趣的:(java设计模式)