ThreadLocal详解

概述

ThreadLocal用来解决多线程环境中资源竞争的问题。它不是通过加锁的方式,而是通过每个线程保存一份资源的副本,这样各个线程访问本线程自己的那一份儿,从而避免了对资源竞争的问题。

用法

ThreadLocal的用法非常的简单,只用操作两个方法即可:

  • set(Tvalue)  往本线程中保存值
  • T get() 从本线程中获取值
下面给出一个实例:
public class ThreadLocalExample {
    public static class MyRunnable implements Runnable {
        private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        public void run() {
            int i = new Random().nextInt(100);
            threadLocal.set(i);
            System.out.println(threadLocal + "---" + Thread.currentThread().getName() + " set- " + i);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {

            }
            System.out.println(threadLocal + "---" + Thread.currentThread().getName() + " get- " + threadLocal.get());
        }
    }

    public static void main(String[] args) {
        MyRunnable sharedRunnableInstance = new MyRunnable();
        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);
        thread1.start();
        thread2.start();
    }
}
程序的输出为:
java.lang.ThreadLocal@53545cc1---Thread-0 set- 18
java.lang.ThreadLocal@53545cc1---Thread-1 set- 41
java.lang.ThreadLocal@53545cc1---Thread-0 get- 18
java.lang.ThreadLocal@53545cc1---Thread-1 get- 41

从输出可以看出,线程Thread-0和线程Thread-1同时操作同一个threadLo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值