1.ThreadLocal的示例
public class ConnThreadLocal {
public static ThreadLocal<String> th = new ThreadLocal<>();
public static void setTh(String value) {
th.set(value);
}
public static void getTh() {
System.out.println(Thread.currentThread().getName() + ": " + th.get());
}
public static void main(String[] args) {
final ConnThreadLocal ct = new ConnThreadLocal();
Thread t1 = new Thread(() -> {
ct.setTh("张三");
ct.getTh();
}, "t1");
Thread t2 = new Thread(() -> {
try {
Thread.sleep(1000);
ct.getTh();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2");
t1.start();
t2.start();
}
}

第二个线程获取全局变量的value时没有得到值。运行结果说明,ThreadLocal保存的是线程的局部变量。
2.单例,推荐
public class Singleton {
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
本文通过示例深入解析了ThreadLocal的工作原理,展示其如何实现线程局部变量的隔离,避免线程间的数据冲突。同时,文章还介绍了单例模式的一种实现方式——静态内部类,探讨其在Java中的应用。

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



