一.ThreadLocal的两大使用场景
典型场景1
每个线程需要一个独享的对象(通常是工具类,典型需要使用的类有SimpleDateFormat和Random),这个对象的特点通常是工具类,这个工具类由于它本身不是线程安全的,所以有多个线程共享同一个静态工具类的话,会有很大风险的,所以需要用到ThreadLocal来帮我们每个线程都创建一个独享的对象,而线程和线程之间呢拥有的工具类是不同的示例,所以之间并不会影响。
第一个场景主要强调每个Thread内有自己的示例副本,不共享。举个例子,如果教材只有一本,一如果多个人一起做笔记,则教材会一团糟,这也就是我们说的线程安全问题。但是如果每个都复制一本教材,就不会出现此问题。
下面先来模拟两个线程分别使用自己的SimpleDateFormat,两个线程都打印日期:
package threadlocal;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 描述: 两个线程打印日期
*/
public class ThreadLocalNormalUsage00 {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage00().date(10);
System.out.println(date);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage00().date(104707);
System.out.println(date);
}
}).start();
}
//传入秒数,转化成日期格式
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT计时
Date date = new Date(1000 * seconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date);
}
}
运行:
到这里,你可能还觉得比较圆满,功能都没有问题。
如果说延伸出30个线程,那就有30个线程和30个SimpleDateFormat,写法如下:
package threadlocal;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 描述: 10个线程打印日期
*/
public class ThreadLocalNormalUsage01 {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 30; i++) {
int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage01().date(finalI);
System.out.println(date);
}
}).start();
Thread.sleep(100);
}
}
//传入秒数,转化成日期格式
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT计时
Date date = new Date(1000 * seconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date);
}
}
到这里,也是依旧能够正常运行的,但是写法有些丑陋。假设有10000个,甚至更多,那么开销将会非常大。但是当需求变成成千上万个时,那必然要用线程池,否则消耗太多内存。我们再对代码进行升级:
package threadlocal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 描述: 1000个打印日期的任务,用线程池来执行
*/
public class ThreadLocalNormalUsage02 {
//用一个固定数量的线程池
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
int finalI = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage02().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
//传入秒数,转化成日期格式
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT计时
Date date = new Date(1000 * seconds);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return dateFormat.format(date);
}
}
但是在这里有一个非常致命的缺点,1000个任务,我们的线程只有10个,但是还是会创建1000个SimpleDateFormat对象。相当于这些对象创建了又销毁,创建了又销毁,因为我们是在date方法里面创建的SimpleDateFormat对象。
那假如我们把SimpleDateFormat单独写出来,只写一个的话,又会如何?
package threadlocal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 描述: 1000个打印日期的任务,用线程池来执行
*/
public class ThreadLocalNormalUsage03 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
int finalI = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage03().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT计时
Date date = new Date(1000 * seconds);
return dateFormat.format(date);
}
}
运行后,问题就来了。会发现出现了相同的时间,这明显是不正确的。
那,这是为什么呢?
这实际上是因为当所有线程都公用一个SimpleDateFormat对象的时候,它发生了线程安全问题。
在这里,所有的线程都指向了SimpleDateFormat对象,而且这个对象本身并不是线程安全的,所以在不同的线程在共同使用这同一个对象的时候,就已经发生了线程安全问题。那么改这么办呢?我们其实可以加锁来解决这个问题。
package threadlocal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 描述: 加锁来解决线程安全问题
*/
public class ThreadLocalNormalUsage04 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
int finalI = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage04().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT计时
Date date = new Date(1000 * seconds);
String s = null;
synchronized (ThreadLocalNormalUsage04.class) {
s = dateFormat.format(date);
}
return s;
}
}
下面来介绍一下更好的解决方案—ThreadLocal来实现一下这个功能:
package threadlocal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 描述: 利用ThreadLocal,给每个线程分配自己的dateFormat对象,保证了线程安全,高效利用内存
*/
public class ThreadLocalNormalUsage05 {
public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 5; i++) {
int finalI = i;
threadPool.submit(new Runnable() {
@Override
public void run() {
String date = new ThreadLocalNormalUsage05().date(finalI);
System.out.println(date);
}
});
}
threadPool.shutdown();
}
public String date(int seconds) {
//参数的单位是毫秒,从1970.1.1 00:00:00 GMT计时
Date date = new Date(1000 * seconds);
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal2.get();
System.out.println(
Thread.currentThread().getName() + ThreadSafeFormatter.dateFormatThreadLocal);
SimpleDateFormat simpleDateFormat = ThreadSafeFormatter.dateFormatThreadLocal.get();
System.out.println(Thread.currentThread().getName() + simpleDateFormat.toString());
System.out.println(
Thread.currentThread().getName() + System.identityHashCode(simpleDateFormat));
return dateFormat.format(date);
}
}
class ThreadSafeFormatter {
//写法1
public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
//写法2
public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal2 = ThreadLocal
.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
典型场景2
每个线程内需要保存全局变量(例如拦截器中获取用户信息),可以让不同方法直接使用,避免参数传递的麻烦。
下面来演示场景二的用法:
package threadlocal;
/**
* 描述: 演示ThreadLocal用法2:避免传递参数的麻烦
*/
public class ThreadLocalNormalUsage06 {
public static void main(String[] args) {
new Service1().process("");
}
}
class Service1 {
public void process(String name) {
User user = new User("超哥");
UserContextHolder.holder.set(user);
new Service2().process();
}
}
class Service2 {
public void process() {
User user = UserContextHolder.holder.get();
ThreadSafeFormatter.dateFormatThreadLocal.get();
System.out.println("Service2拿到用户名:" + user.name);
new Service3().process();
}
}
class Service3 {
public void process() {
User user = UserContextHolder.holder.get();
System.out.println("Service3拿到用户名:" + user.name);
UserContextHolder.holder.remove();
}
}
// 定义ThreadLocal
class UserContextHolder {
public static ThreadLocal<User> holder = new ThreadLocal<>();
}
class User {
String name;
public User(String name) {
this.name = name;
}
}
我们新建很多的Service类来模拟User对象参数传递。
二.ThreadLocal的作用和主要方法