入门案例
package com.che.springbootdemo.thread;
/**
* @author cyh
* @Description
* @date 2022/4/11 20:57
* 在多线程下操作共享数据时,通过ThreadLocal来维护每个线程的数据安全
*/
public class ThreadLocalTest {
private ThreadLocal<String> threadLocal=new ThreadLocal<>();
private String content;
public String getContent() {
return threadLocal.get();
}
public void setContent(String content) {
threadLocal.set(content);
}
public static void main(String[] args) {
ThreadLocalTest test = new ThreadLocalTest();
for (int i = 0; i < 10; i++) {
new Thread(()->{
test.setContent(Thread.currentThread().getName()+"的数据");
System.out.println(Thread.currentThread().getName()+"--->"+test.getContent());
},"线程"+i).start();
}
}
}
ThreadLocal和Synchronized区别
运用场景
ThreadLocal内部结构
ThreadLocal核心方法源码
Set方法
get方法
remove方法
initialValue方法