徹底搞懂Java多線程(四)
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 之後:
總結
本篇文章就到這裡瞭,希望對你有些幫助,也希望你可以多多關註WalkonNet的更多內容!
推薦閱讀:
- Java之ThreadLocal使用常見和方式案例講解
- Java線程池使用AbortPolicy策略
- Java技能點之SimpleDateFormat進行日期格式化問題
- 徹底搞懂Java多線程(三)
- java Date和SimpleDateFormat時間類詳解