ThreadLocal的使用和底层结构

ThreadLocal的使用和底层结构,第1张

ThreadLocal的使用和底层结构

1、ThreadLocal的作用:

提供线程内的局部变量,不同线程之间不会相互干扰,线程之间相互隔离。

2、ThreadLocal的原理:

在多线程下 *** 作共享变量,如果不加ThreadLocal,那么 多个线程 *** 控的是同一个共享变量,加了ThreadLocal,每个线程会保存一份共享变量,各个线程 *** 控自己线程的变量,线程之间相互隔离,互不影响。

3、ThreadLocal的基本使用:

package com.zx.threadlocaldemo;

public class threadlocalDome {

    ThreadLocal threadLocal1=new ThreadLocal<>();

    ThreadLocal threadLocal2=new ThreadLocal<>();

    private String content;

    private String title;

    public String getTitle() {
        return threadLocal2.get();
    }

    public void setTitle(String title) {
        threadLocal2.set(title);
    }

    public String getContent() {
        return threadLocal1.get();
    }

    public void setContent(String content) {
        //this.content = content;
        threadLocal1.set(content);
    }


    public static void main(String[] args) {
        threadlocalDome dome=new threadlocalDome();
        for(int i=0;i<5;i++){
            Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    dome.setContent(Thread.currentThread().getName()+"的数据");
                    dome.setTitle(Thread.currentThread().getName()+"的标题");
                    System.out.println("---------------------------");
                    System.out.println(Thread.currentThread().getName()+"--->"+dome.getContent());
                    System.out.println(Thread.currentThread().getName()+"--->"+dome.getTitle());
                }
            });
            thread.setName("线程"+i);
            thread.start();
        }
    }




}

 4、ThreadLocal的底层结构:

Thread类中有一个属性threadlocals,类型为ThreadLocalMap,以键值对的形式存储,key值为ThreadLocal的实例,value为变量副本的值。

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5709851.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存