Java ThreadLocal应用

定义

使用ThreadLocal定义的变量,为每一个线程都提供一个线程独立的副本。简单一点,一个线程一个单例。

简单实例

import java.util.Random;
public class ThreadLocalTestMain {
    public static void main(String[] args) throws Throwable {
        Thread t= new Thread(()->{
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
        });
        Thread t2= new Thread(()->{
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
        });
        Thread t3= new Thread(()->{
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ID值:"+ThreadLocalTest.getId());
        });
        t.start();
        t2.start();
        t3.start();
    }
    public static class ThreadLocalTest {
        private static ThreadLocal<Integer> ids = ThreadLocal.withInitial(() -> {
            System.out.println("线程ID"+Thread.currentThread().getId()+ ";ids值初始化");
            return  new Random().nextInt(10000);
        });
        public static Integer getId() {
            return ids.get();
        }
    }

}

输出结果

线程ID12;ids值初始化
线程ID14;ids值初始化
线程ID13;ids值初始化
线程ID12;ID值:2137
线程ID14;ID值:7831
线程ID13;ID值:1443
线程ID13;ID值:1443
线程ID13;ID值:1443
线程ID13;ID值:1443
线程ID13;ID值:1443

结果分析

1:每个线程都会有且只有一次初始化。
2:一个线程只调用gid,并不会再触初始化。
3:综合上面1,2结论,得出:一个程线一个单例。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值