彻底搞懂Java多线程(四)
目录
- SimpleDateFormat非线程安全问题
- ThreadLocal
- ThreadLocal的原理
- ThreadLocal常用方法
- ThreadLocal的初始化
- InheritableThreadLocal的使用
- 总结
SimpleDateFormat非线程安全问题
实现1000个线程的时间格式化
package SimpleDateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * user:ypc; * date:2021-06-13; * time: 17:30; */ public class SimpleDateFormat1 { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10,10,100, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(1000),new ThreadPoolExecutor.DiscardPolicy()); for (int i = 0; i < 1001; i++) { int finalI = i; threadPoolExecutor.submit(new Runnable() { @Override public void run() { Date date = new Date(finalI * 1000); myFormatTime(date); } }); } threadPoolExecutor.shutdown(); } private static void myFormatTime(Date date){ System.out.println(simpleDateFormat.format(date)); } }
产生了线程不安全的问题👇:
这是因为:
多线程的情况下:
线程1在时间片用完之后,线程2来setTime()那么线程1的得到了线程2的时间。
所以可以使用加锁的操作:
就不会有重复的时间了
但是虽然可以解决线程不安全的问题,但是排队等待锁,性能就会变得低
所以可以使用局部变量:
也解决了线程不安全的问题:
但是每次也都会创建新的私有变量
那么有没有一种方案既可以避免加锁排队执行,又不会每次创建任务的时候不会创建私有的变量呢?
那就是ThreadLocal👇:
ThreadLocal
ThreadLocal的作用就是让每一个线程都拥有自己的变量。
那么选择锁还是ThreadLocal?
看创建实列对象的复用率,如果复用率比较高的话,就使用ThreadLocal。
ThreadLocal的原理
类ThreadLocal的主要作用就是将数据放到当前对象的Map中,这个Map时thread类的实列变量。类ThreadLocal自己不管理、不存储任何的数据,它只是数据和Map之间的桥梁。
执行的流程:数据—>ThreadLocal—>currentThread()—>Map。
执行后每个Map存有自己的数据,Map中的key中存储的就是ThreadLocal对象,value就是存储的值。每个Thread的Map值只对当前的线程可见,其它的线程不可以访问当前线程对象中Map的值。当前的线程被销毁,Map也随之被销毁,Map中的数据如果没有被引用、没有被使用,则随时GC回收。
ThreadLocal常用方法
set(T):将内容存储到ThreadLocal
get():从线程去私有的变量
remove():从线程中移除私有变量
package ThreadLocalDemo; import java.text.SimpleDateFormat; /** * user:ypc; * date:2021-06-13; * time: 18:37; */ public class ThreadLocalDemo1 { private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { //设置私有变量 threadLocal.set(new SimpleDateFormat("mm:ss")); //得到ThreadLocal SimpleDateFormat simpleDateFormat = threadLocal.get(); //移除 threadLocal.remove(); } }
ThreadLocal的初始化
ThreadLocal提供了两种初始化的方法
initialValue()和
initialValue()初始化:
package ThreadLocalDemo; import java.text.SimpleDateFormat; import java.util.Date; /** * user:ypc; * date:2021-06-13; * time: 19:07; */ public class ThreadLocalDemo2 { //创建并初始化ThreadLocal private static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal() { @Override protected SimpleDateFormat initialValue() { System.out.println(Thread.currentThread().getName() + "执行了自己的threadLocal中的初始化方法initialValue()"); return new SimpleDateFormat("mm:ss"); } }; public static void main(String[] args) { Thread thread1 = new Thread(() -> { Date date = new Date(5000); System.out.println("thread0格式化时间之后得结果时:" + threadLocal.get().format(date)); }); thread1.setName("thread0"); thread1.start(); Thread thread2 = new Thread(() -> { Date date = new Date(6000); System.out.println("thread1格式化时间之后得结果时:" + threadLocal.get().format(date)); }); thread2.setName("thread1"); thread2.start(); } }
withInitial方法初始化:
package ThreadLocalDemo; import java.util.function.Supplier; /** * user:ypc; * date:2021-06-14; * time: 17:23; */ public class ThreadLocalDemo3 { private static ThreadLocal<String> stringThreadLocal = ThreadLocal.withInitial(new Supplier<String>() { @Override public String get() { System.out.println("执行了withInitial()方法"); return "我是" + Thread.currentThread().getName() + "的ThreadLocal"; } }); public static void main(String[] args) { Thread thread1 = new Thread(() -> { System.out.println(stringThreadLocal.get()); }); thread1.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { System.out.println(stringThreadLocal.get()); } }); thread2.start(); } }
注意:
ThreadLocal如果使用了set()方法的话,那么它的初始化方法就不会起作用了。
来看:👇
package ThreadLocalDemo; /** * user:ypc; * date:2021-06-14; * time: 18:43; */ class Tools { public static ThreadLocal t1 = new ThreadLocal(); } class ThreadA extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("在ThreadA中取值:" + Tools.t1.get()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadLocalDemo4 { public static void main(String[] args) throws InterruptedException { //main是ThreadA 的 父线程 让main线程set,ThreadA,是get不到的 if (Tools.t1.get() == null) { Tools.t1.set("main父线程的set"); } System.out.println("main get 到了: " + Tools.t1.get()); Thread.sleep(1000); ThreadA a = new ThreadA(); a.start(); } }
类ThreadLocal不能实现值的继承,那么就可以使用InheritableThreadLocal了👇
InheritableThreadLocal的使用
使用InheritableThreadLocal可以使子线程继承父线程的值
在来看运行的结果:
子线程有最新的值,父线程依旧是旧的值
package ThreadLocalDemo; /** * user:ypc; * date:2021-06-14; * time: 19:07; */ class ThreadB extends Thread{ @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println("在ThreadB中取值:" + Tools.t1.get()); if (i == 5){ Tools.t1.set("我是ThreadB中新set()"); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadLocalDemo5 { public static void main(String[] args) throws InterruptedException { if (Tools.t1.get() == null) { Tools.t1.set("main父线程的set"); } System.out.println("main get 到了: " + Tools.t1.get()); Thread.sleep(1000); ThreadA a = new ThreadA(); a.start(); Thread.sleep(5000); for (int i = 0; i < 10; i++) { System.out.println("main的get是:" + Tools.t1.get()); Thread.sleep(100); } } }
ThreadLocal的脏读问题来看👇
package ThreadLocalDemo; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * user:ypc; * date:2021-06-14; * time: 19:49; */ public class ThreadLocalDemo6 { private static ThreadLocal<String> threadLocal = new ThreadLocal<>(); private static class MyThread extends Thread { private static boolean flag = false; @Override public void run() { String name = this.getName(); if (!flag) { threadLocal.set(name); System.out.println(name + "设置了" + name); flag = true; } System.out.println(name + "得到了" + threadLocal.get()); } } public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(10)); for (int i = 0; i < 2; i++) { threadPoolExecutor.execute(new MyThread()); } threadPoolExecutor.shutdown(); } }
发生了脏读:
线程池复用了线程,也复用了这个线程相关的静态属性,就导致了脏读
那么如何避免脏读呢?
去掉static 之后:
总结
本篇文章就到这里了,希望对你有些帮助,也希望你可以多多关注我们的更多内容!