线程封闭之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对象。

猜你喜欢

转载自blog.csdn.net/hellboy0621/article/details/106152435