ThreadLocal

本文详细介绍了Java中的ThreadLocal机制,它为每个线程提供独立的变量副本,确保线程安全。示例代码展示了如何使用ThreadLocal创建线程局部变量,并在多线程环境中进行操作。通过initialValue方法设置初始值,set和get方法进行值的设置和获取,以及ThreadLocalMap的内部实现。
摘要由CSDN通过智能技术生成

基于《java编程第四版》的相关代码

/**
 * 线程本地存储
 * 相当于为每个线程开启了一个map,存放属于自己的特有对象或者值
 */
public class ThreadLocalVariableHolder {
    private static ThreadLocal<Integer> value = new ThreadLocal<Integer>(){
        private Random rand = new Random(47);
        protected  synchronized  Integer initialValue(){
            return rand.nextInt(10000);
        }
    };
    public static  void increment(){
        value.set(value.get()+1);
    }
    public static int get(){
        return value.get();
    }

    public static void main(String[] args) throws Exception{
        ExecutorService exec = Executors.newCachedThreadPool();
        for(int i = 0 ; i < 5 ; i++){
            exec.execute(new Access(i));
        }
        TimeUnit.MILLISECONDS.sleep(100);
        exec.shutdownNow();
    }
}
class Access implements Runnable{
    private final int id;
    public Access(int idn){
        this.id = idn;
    }
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            ThreadLocalVariableHolder.increment();
            System.out.println(this);
            Thread.yield();
        }
    }

    @Override
    public String toString() {
        return "#" + id + ':' + ThreadLocalVariableHolder.get();
    }
}

1.线程(Thread)

/* 与此线程有关的ThreadLocal值。该映射由ThreadLocal类维护。*/
ThreadLocal.ThreadLocalMap threadLocals = null;

2.ThreadLocal

(1)重写initialValue方法

private Random rand = new Random(47);
protected  synchronized  Integer initialValue(){
    return rand.nextInt(10000);
}

(2)set方法

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

(3)get方法

public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);//获取当前线程对应的ThreadLocalMap
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

(4)其他方法

a.getMap方法

ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

b.setInitialValue方法

private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值