ThreadLocal 相关知识点
问题演示
当我们在多线程的情况下需要对共享变量进行修改时,就有可能会引发线程安全问题。对于这种情况,我们可以使用 ThreadLocal 来解决这个问题。
public class Demo {public static final String str = "test";public static void main(String[] args) {ThreadLocal<String> threadLocal = new ThreadLocal<>() {@Overrideprotected String initialValue() {return str;}};Thread thread1 = new Thread(() -> {String string = threadLocal.get();string = "thread1 test";threadLocal.set(string);System.out.println(threadLocal.get());});Thread thread2 = new Thread(() -> {String string = threadLocal.get();string = "thread2 test";threadLocal.set(string);System.out.println(threadLocal.get());});Thread thread3 = new Thread(() -> { //对比组System.out.println(threadLocal.g