0
点赞
收藏
分享

微信扫一扫

ThreadLocal使用案例

开源分享 2022-01-17 阅读 46
java

ThreadLocal功能测试【每个线程都有一个自己的本地变量】

class ThreadLocalExample implements Runnable{

// SimpleDateFormat 不是线程安全的,所以每个线程都要有自己独立的副本
private static final ThreadLocal<SimpleDateFormat> formatter = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd HHmm"));

public static void main(String[] args) throws InterruptedException {
ThreadLocalExample obj = new ThreadLocalExample();
for(int i=0 ; i<5; i++){
Thread t = new Thread(obj, ""+i);
Thread.sleep(new Random().nextInt(1000));
t.start();
}
}

@Override
public void run() {
System.out.println("Thread Name= "+Thread.currentThread().getName()+" default Formatter = "+formatter.get().toPattern());
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
//SimpleDateFormat 在此处由线程更改,但不会反映到其他线程
formatter.set(new SimpleDateFormat());

System.out.println("Thread Name= "+Thread.currentThread().getName()+" formatter = "+formatter.get().toPattern());
}

}

输出结果:【不会影响主内存变量】

Thread Name= 0 default Formatter = yyyyMMdd HHmm
Thread Name= 0 formatter = yy-M-d ah:mm
Thread Name= 1 default Formatter = yyyyMMdd HHmm
Thread Name= 2 default Formatter = yyyyMMdd HHmm
Thread Name= 3 default Formatter = yyyyMMdd HHmm
Thread Name= 2 formatter = yy-M-d ah:mm
Thread Name= 1 formatter = yy-M-d ah:mm
Thread Name= 4 default Formatter = yyyyMMdd HHmm
Thread Name= 3 formatter = yy-M-d ah:mm
Thread Name= 4 formatter = yy-M-d ah:mm

使用案例一

在这里插入图片描述
在这里插入图片描述

使用案例二

@Component
public class CheckTimeUtil implements InitializingBean {

private static final String YYYYMMDD = "yyyyMMdd";
private static final String YYYYMM = "yyyyMM";
private static Integer deadline;
private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<>();
private static Object lock = new Object();

private static SimpleDateFormat getSdf(final String pattern) {
ThreadLocal<SimpleDateFormat> threadLocal = sdfMap.get(pattern);
if (null == threadLocal) {
synchronized (lock) {
threadLocal = sdfMap.get(pattern);
if (null == threadLocal) {
threadLocal = ThreadLocal.withInitial(() -> {
return new SimpleDateFormat(pattern);
});
sdfMap.put(pattern,threadLocal);
}
}
}
return threadLocal.get();
}
}
举报

相关推荐

0 条评论