ThreadLocal

  • ThreadLocal线程局部变量,不同的线程有各自的副本。通过set存入值,get取出值,各线程间不互相影响。
  • 创建10个线程。对于普通变量count,10个线程在不断累加。对于ThreadLocal的变量tCount各个线程是相互隔离的。
public class ThreadLocalTest {

    public static void main(String[] args) {

        Runnable r = new R();
        for(int i=0; i<10;i++){
            new Thread(r).start();
        }
    }
    static class R implements  Runnable{

        private Integer count = 0;

        private ThreadLocal<Integer> tCount = new ThreadLocal<Integer>(){
            @Override
            protected Integer initialValue() { //初始化存入的值
                return 0;
            }
        };

        public void add(){
            count = count + 5;
            tCount.set(tCount.get()+5);
        }

        @Override
        public void run() {
            add();
            System.out.println("count:"+count+"  tCount:"+tCount.get());
        }
    }
}

运行结果如下。

count:5  tCount:5
count:10  tCount:5
count:15  tCount:5
count:20  tCount:5
count:30  tCount:5
count:25  tCount:5
count:35  tCount:5
count:40  tCount:5
count:45  tCount:5
count:50  tCount:5

  • Thread类中有一个成员变量ThreadLocalMap。在这map中key是ThreadLocal,值是你存入的值。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值