一、为什么要使用ThreadLocal?
1.1、概述
并发场景下,会存在多个线程同时修改一个共享变量的场景,这就有可能会出现线程安全的问题。为了解决线程安全问题,可以用加锁的方式,比如对核心代码使用synchronized或者Lock进行加锁,从而起到线程隔离的效果。但是加锁的方式,在高并发下会导致系统变慢,加锁示意图如下:
还有另外一种方案,就是使用空间换时间的方式,即:使用ThreadLocal,使用ThreadLocal访问共享变量时,会在每个线程本地保存一份共享变量的副本。多线程对共享变量修改时,实际上每个线程操作的是自己的变量副本,从而保证线程安全。示意图如下:
1.2、线程不安全案例
/**
* @Author : 一叶浮萍归大海
* @Date: 2024/2/26 11:15
* @Model Description:
* @Description: 线程不安全案例
*/
@Data
public class ThreadLocalDemo1MainApp {
/**
* 共享变量
*/
private String content;
public static void main(String[] args) {
ThreadLocalDemo1MainApp demo1 = new ThreadLocalDemo1MainApp();
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
demo1.setContent(Thread.currentThread().getName() + "的数据");
System.out.println("==================");
System.out.println(Thread.currentThread().getName() + "=====>" + demo1.getContent());
}, "线程" + String.valueOf(i)).start();
}
}
}
1.3、线程不安全案例(ThreadLocal解决)
/**
* @Author : 一叶浮萍归大海
* @Date: 2024/2/26 11:15
* @Model Description:
* @Description: 使用ThreadLocal解决线程不安全案例
*/
public class ThreadLocalDemo2MainApp {
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) {
ThreadLocalDemo2MainApp demo2 = new ThreadLocalDemo2MainApp();
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
demo2.setContent(Thread.currentThread().getName() + "的数据");
System.out.println("==================");
System.out.println(Thread.currentThread().getName() + "=====>" + demo2.getContent());
}, "线程" + String.valueOf(i)).start();
}
}
}

1.4、线程不安全案例(synchronized解决)
/**
* @Author : 一叶浮萍归大海
* @Date: 2024/2/26 11:15
* @Model Description:
* @Description: 使用synchronized解决线程不安全案例
*/
@Data
public class ThreadLocalDemo3MainApp {
/**
* 共享变量
*/
private String content;
public static void main(String[] args) {
ThreadLocalDemo3MainApp demo3 = new ThreadLocalDemo3MainApp();
for (int i = 1; i <= 5; i++) {
new Thread(() -> {
synchronized (ThreadLocalDemo3MainApp.class) {
demo3.setContent(Thread.currentThread().getName() + "的数据");
System.out.println("==================");
System.out.println(Thread.currentThread().getName() + "=====>" + demo3.getContent());
}
}, "线程" + String.valueOf(i)).start();
}
}
}



551

被折叠的 条评论
为什么被折叠?



