java里ThreadLocal的使用

14 篇文章 0 订阅

ThreadLocal的作用:
使变量在每个线程独立

ThreadLocal的使用:

ThreadLocal threadLocal = new ThreadLocal<>(); //创建ThreadLocal对象(有泛型,多个对象创建多个ThreadLocal对象)
threadLocal.set(T t); //设置变量 T temp = threadLocal.get();//读取变量
threadLocal.remove(); //释放资源,防止内存泄漏

例:
没有使用ThreadLocal

public class MyRunnable implements Runnable{

    private Integer id = 0;

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是 "+Thread.currentThread().getName()+" 的id: "+(++id));
        }

    }

}
public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    for (int i = 0; i < 50; i++) {
        new Thread(myRunnable).start();
    }
}

结果:

我是 Thread-0 的id: 1
我是 Thread-0 的id: 2
我是 Thread-0 的id: 3
我是 Thread-0 的id: 4
...
我是 Thread-20 的id: 4993
我是 Thread-20 的id: 4994
我是 Thread-20 的id: 4995
我是 Thread-20 的id: 4996
我是 Thread-15 的id: 4984
我是 Thread-15 的id: 4997
我是 Thread-15 的id: 4998

Process finished with exit code 0

使用ThreadLocal

public class MyRunnable implements Runnable{

    private Integer id = 0;

    @Override
    public void run() {
        ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        threadLocal.set(id);
        for (int i = 0; i < 100; i++) {
            Integer temp = threadLocal.get();
            System.out.println("我是 "+Thread.currentThread().getName()+" 的id: "+(++temp));
            threadLocal.set(temp);
        }
        threadLocal.remove();//释放资源
    }

}
public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    for (int i = 0; i < 50; i++) {
        new Thread(myRunnable).start();
    }
}

结果:

我是 Thread-1 的id: 1
我是 Thread-1 的id: 2
我是 Thread-1 的id: 3
我是 Thread-1 的id: 4
我是 Thread-1 的id: 5
我是 Thread-1 的id: 6
...
我是 Thread-19 的id: 94
我是 Thread-19 的id: 95
我是 Thread-19 的id: 96
我是 Thread-19 的id: 97
我是 Thread-19 的id: 98
我是 Thread-19 的id: 99
我是 Thread-19 的id: 100

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值