一、ThreadLocal的使用
- 在保证线程安全中,我们除了控制资源的访问外(锁),还可以通过增加资源来保证线程安全。ThreadLocal主要解决了为每一个线程绑定各自的资源。
static ThreadLocal threadLocal = new ThreadLocal();
static class myThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++){
//设置线程关联的值
threadLocal.set(Thread.currentThread().getName()+" - "+ (i+1));
//读线程的值
System.out.println(Thread.currentThread().getName()+" - value:" + threadLocal.get());
}
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new myThread());
Thread thread2 = new Thread(new myThread());
thread1.start();
thread2.start();
}
运行结果:
- 从运行结果可以看出每个线程都有它们自己的变量值,它们的i都被加到了10。ThreadLocal相当于就是个容器,为每个线程保存它们的变量,多个线程之间互不干涉。
二、ThreadLocal支持泛型
- 现在有一个例子,在多线程环境当中,将字符串转化为一个日期对象
//在多线程环境中,把字符串转换为日期对象
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
static class MyThread implements Runnable {
private int i = 0;
public MyThread(int i) {
this.i = i;
}
@Override
public void run() {
String str = "2020年6月2日 09:19:" + i%60;
try {
Date date = sdf.parse(str);
System.out.println(i + "-----" +date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//创建一百个线程
for (int i = 0; i < 100;i++){
new Thread(new MyThread(i)).start();
}
}
运行结果:出现了一大堆异常,因为所有的线程都使用一个SimpleDateFormat对象,这样会有多线程安全问题。这个时候我们就需要使用ThreadLocal来解决。
//在多线程环境中,把字符串转换为日期对象
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<> ();
static class MyThread implements Runnable {
private int i = 0;
public MyThread(int i) {
this.i = i;
}
@Override
public void run() {
String str = "2020年6月2日 09:19:" + i%60;
try {
/*Date date = sdf.parse(str);
System.out.println(i + "-----" +date);*/
if(threadLocal.get()==null){
threadLocal.set(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"));
}
Date date = threadLocal.get().parse(str);
System.out.println(i + "-----" +date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//创建一百个线程
for (int i = 0; i < 100;i++){
new Thread(new MyThread(i)).start();
}
}
运行结果:
- 在代码中添加ThreadLocal对象,并使用它的泛型,因为这里多线程共享一个SimpleDateFormat对象,所以泛型就是SimpleDateFormat,当线程抢到了时间片执行时,先判断他有没有被分配它自己的SimpleDateFormat对象,没有就给它一个,有了以后,就用他自己的SimpleDateFormat对象来拿到一个日期对象,这样就没有线程安全问题了。
三、ThreadLocal的初始值
- 如果我们定义了一个ThreadLocal对象,但是这个对象从来没有set过内容,那么当调用这个ThreadLocal对象的get方法时,返回的是一个null,所以ThreadLocal没有初始值。
- 我们可以定义一个ThreadLocal的子类,继承ThreadLocal后,重写父类的initialValue方法,可以返回一个当前日期作为初始值,进行初始化。(当然也可以设置成其他内容)
public class MyThreadLocal extends ThreadLocal<Date>{
@Override
protected Date initialValue() {
return new Date();
}
}