线程封闭之ThreadLocal

多线程访问共享可变数据时,涉及到线程间数据同步问题。

数据都被封闭在各自的线程之中,就不需要同步,这种通过将数据封闭在线程中,而避免使同步的技术,称为线程封闭。

ThreadLocal

  • 线程级别变量
  • 每个线程都有一个ThreadLocal
  • 每个线程都拥有了自己独立的一个变量
  • 竞争条件被彻底消除了
  • 在并发模式下是绝对安全的变量

1.示例

import java.text.SimpleDateFormat;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo implements Runnable {

    ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(threadLocalDemo, String.valueOf(i));
            TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
            thread.start();
        }
    }

    @Override
    public void run() {
        System.out.println("Thread name = " + Thread.currentThread().getName()
                + ", default formatter = " + simpleDateFormatThreadLocal.get().toPattern());
        try {
            TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        simpleDateFormatThreadLocal.set(new SimpleDateFormat());
        System.out.println("Thread name = " + Thread.currentThread().getName()
                + ", formatter = " + simpleDateFormatThreadLocal.get().toPattern());
    }
}

输出

Thread name = 0, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 0, formatter = yy-M-d ah:mm
Thread name = 1, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 2, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 1, formatter = yy-M-d ah:mm
Thread name = 3, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 2, formatter = yy-M-d ah:mm
Thread name = 3, formatter = yy-M-d ah:mm
Thread name = 4, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 5, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 4, formatter = yy-M-d ah:mm
Thread name = 5, formatter = yy-M-d ah:mm
Thread name = 6, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 6, formatter = yy-M-d ah:mm
Thread name = 7, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 8, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 8, formatter = yy-M-d ah:mm
Thread name = 9, default formatter = yyyy-MM-dd HH:mm:ss
Thread name = 7, formatter = yy-M-d ah:mm
Thread name = 9, formatter = yy-M-d ah:mm

虽然Thread-0已经改变了formatter的值,显然其他线程的默认formatter格式没有受到影响。

2.原理分析

在Thread类中有如下属性

/* ThreadLocal values pertaining to this thread. This map is maintained
 * by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

默认情况下,threadLocals属性值为null。只有当调用ThreadLocal的set()、get()方法时,如果为null则调用createMap()赋初值。

/**
 * Sets the current thread's copy of this thread-local variable
 * to the specified value.  Most subclasses will have no need to
 * override this method, relying solely on the {@link #initialValue}
 * method to set the values of thread-locals.
 *
 * @param value the value to be stored in the current thread's copy of
 *        this thread-local.
 */
public void set(T value) {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

/**
 * Get the map associated with a ThreadLocal. Overridden in
 * InheritableThreadLocal.
 *
 * @param  t the current thread
 * @return the map
 */
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

/**
 * Create the map associated with a ThreadLocal. Overridden in
 * InheritableThreadLocal.
 *
 * @param t the current thread
 * @param firstValue value for the initial entry of the map
 */
void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

 最终,变量存储在ThreadLocalMap中,key为ThreadLocal对象。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值