-
ThreadLocal :维护每个线程的对象信息,原理:threaLocal为每个线程维护一个threadLocalmap,其中threalocal作为map的key,set进去的值作为线程的map的value【线程池中线程可能永远不会被销毁,所以需要手动移除线程中的value,避免内存泄漏】
-
代码示例:
-
一个用threadLocal处理的java类:
package com.example.demo.xc;
public class Person {
/**
* 缓存当前线程操作的对象信息 原理是每个线程中维护一个map,吧当前threadlocal对象当做线程的key,吧set进来的值当做线程的value
*/
private ThreadLocal threadLocal = new ThreadLocal();
public void setName(String name) {
this.threadLocal.set(name);
}
public String getName() {
return this.threadLocal.get().toString();
}
/**
* 线程池用线程可能不会被销毁,时间长造成内存泄漏,需要手动移除
*/
public void remove(){
threadLocal.remove();
}
}
-测试每个线程取值:
package com.example.demo.xc;
import lombok.SneakyThrows;
public class App {
public static void main(String[] args) {
Person person = new Person();
new Thread(new Runnable() {
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
person.setName("金旭东");
Thread.sleep(2000L);
System.out.println("线程1:" + person.getName());
person.remove();
}
}).start();
new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
person.setName("范冰冰");
Thread.sleep(2000L);
System.out.println("线程2:" + person.getName());
person.remove();
}
}).start();
}
}
- ThreadLocal处理SImpleDateFormat
package com.example.demo.xc;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期工具类
*/
public class DateUtil {
/**
* 处理simpleDateFormat线程安全 每个线程维护一个simpleDateFormat
*/
private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal() {
@Override
protected Object initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
/**
* 格式化日期
*
* @return
*/
public static String formatDate(Date date) {
return threadLocal.get().format(date);
}
public static Date parseDate(String string) throws Exception {
return threadLocal.get().parse(string);
}
}
- 测试
for (int i = 0; i < 100; i++) {
new Thread(() -> {
try {
String string = DateUtil.formatDate(new Date());
Date date = DateUtil.parseDate(string);
System.out.println(string.endsWith(DateUtil.formatDate(date)));
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}