1. 程式人生 > >這或許是最詳細的JUC多執行緒併發總結

這或許是最詳細的JUC多執行緒併發總結

# 多執行緒進階---JUC併發程式設計 ==**完整程式碼傳送門,見文章末尾**== ## 1.Lock鎖(重點) > 傳統 Synchronizd ```java package com.godfrey.demo01; /** * description : 模擬賣票 * * @author godfrey * @since 2020-05-14 */ public class SaleTicketDemo01 { public static void main(String[] args) { Ticket ticket = new Ticket(); new Thread(() -> { for (int i = 0; i < 60; i++) { ticket.sale(); } }, "A").start(); new Thread(() -> { for (int i = 0; i < 60; i++) { ticket.sale(); } }, "B").start(); new Thread(() -> { for (int i = 0; i < 60; i++) { ticket.sale(); } }, "C").start(); } } //資源類OOP class Ticket { private int number = 50; public synchronized void sale() { if (number >
0) { System.out.println(Thread.currentThread().getName() + "賣出了第" + (50 - (number--)) + "票,剩餘:" + number); } } } ``` > Synchronized(本質:佇列+鎖)和Lock區別 1. Synchronized 是內建關鍵字,Lock 是一個Java類 2. Synchronized 無法判斷鎖的狀態,Lock 可以判斷是否獲取到了鎖 3. Synchronized 會自動釋放鎖,Lock 必須手動釋放!如果不釋放鎖,**死鎖** 4. Synchronized 執行緒1(獲得鎖,阻塞)、執行緒2(等待,傻傻的等);Lock 鎖就不一定會等待下去(tryLock) 5. Synchronized 可重入鎖,不可中斷,非公平;Lock 可重入鎖 ,可以判斷鎖,非公平(可以自己設定); 6. Synchronized 適合鎖少量的程式碼同步問題,Lock 適合鎖大量的同步程式碼! >
鎖是什麼,如何判斷鎖的是誰 ## 2.執行緒之間通訊問題:生成者消費者問題 > Synchronized版生產者消費者問題 ```java package proc; /** * description : 生產者消費者問題 * * @author godfrey * @since 2020-05-14 */ public class A { public static void main(String[] args) { Data data = new Data(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); } } // 判斷等待,業務,通知 class Data { private int number = 0; //+1 public synchronized void increment() throws InterruptedException { if (number != 0) { //等待 this.wait(); } number++; System.out.println(Thread.currentThread().getName() + "==>
" + number); //通知其他執行緒,我+1完畢了 this.notifyAll(); } //-1 public synchronized void decrement() throws InterruptedException { if (number == 0) { //等待 this.wait(); } number--; System.out.println(Thread.currentThread().getName() + "==>" + number); //通知其他執行緒,我-1完畢了 this.notifyAll(); } } ``` > Lock介面 ![](http://imgcloud.duiyi.xyz//data20200515214119.png) ![](http://imgcloud.duiyi.xyz//data20200515214156.png) ![](http://imgcloud.duiyi.xyz//data20200515214340.png) 公平鎖:十分公平:可以先來後到 **非公平鎖:十分不公平:可以插隊 (預設)** ```java package com.godfrey.demo01; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * description : 模擬賣票 * * @author godfrey * @since 2020-05-14 */ public class SaleTicketDemo02 { public static void main(String[] args) { Ticket ticket = new Ticket(); new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale(); }, "A").start(); new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale(); }, "B").start(); new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale(); }, "C").start(); } } //Lock class Ticket2 { private int number = 30; Lock lock = new ReentrantLock(); public synchronized void sale() { lock.lock(); try { if (number > 0) { System.out.println(Thread.currentThread().getName() + "賣出了第" + (50 - (number--)) + "票,剩餘:" + number); } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } ``` > 問題存在,ABCD四個執行緒!怎麼解決? ![](http://imgcloud.duiyi.xyz//data20200514172432.png) if ==>while ```java package com.godfrey.proc; /** * description : Synchronized版生成者消費者問題 * * @author godfrey * @since 2020-05-14 */ public class A { public static void main(String[] args) { Data data = new Data(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "C").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "D").start(); } } // 判斷等待,業務,通知 class Data { private int number = 0; //+1 public synchronized void increment() throws InterruptedException { while (number != 0) { //等待 this.wait(); } number++; System.out.println(Thread.currentThread().getName() + "==>" + number); //通知其他執行緒,我+1完畢了 this.notifyAll(); } //-1 public synchronized void decrement() throws InterruptedException { while (number == 0) { //等待 this.wait(); } number--; System.out.println(Thread.currentThread().getName() + "==>" + number); //通知其他執行緒,我-1完畢了 this.notifyAll(); } } ``` > JUC版的生產者和消費者問題 通過Lock ```java package com.godfrey.proc; /** * description : Lock版生產者消費者問題 * * @author godfrey * @since 2020-05-14 */ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class B { public static void main(String[] args) { Data2 data = new Data2(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "C").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { try { data.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "D").start(); } } // 判斷等待,業務,通知 class Data2 { private int number = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); //+1 public void increment() throws InterruptedException { lock.lock(); try { while (number != 0) { //等待 condition.await(); } number++; System.out.println(Thread.currentThread().getName() + "==>" + number); //通知其他執行緒,我+1完畢了 condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } //-1 public void decrement() throws InterruptedException { lock.lock(); try { while (number == 0) { //等待 condition.await(); } number--; System.out.println(Thread.currentThread().getName() + "==>" + number); //通知其他執行緒,我-1完畢了 condition.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } ``` > Condition的優勢:精準通知和喚醒執行緒 ![](http://imgcloud.duiyi.xyz//data20200515073048.png). ```java package com.godfrey.proc; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * description : 按順序執行 A->B->C * * @author godfrey * @since 2020-05-15 */ public class C { public static void main(String[] args) { Data3 data = new Data3(); new Thread(() -> { for (int i = 0; i < 10; i++) { data.printA(); } }, "A").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { data.printB(); } }, "B").start(); new Thread(() -> { for (int i = 0; i < 10; i++) { data.printC(); } }, "C").start(); } } //資源類 class Data3 { private Lock lock = new ReentrantLock(); private Condition condition1 = lock.newCondition(); private Condition condition2 = lock.newCondition(); private Condition condition3 = lock.newCondition(); private int number = 1; //1A 2B 3C public void printA() { lock.lock(); try { //業務,判斷->執行->通知 while (number != 1) { //等待 condition1.await(); } System.out.println(Thread.currentThread().getName() + "=>AAAAA"); //通知指定的人,B number = 2; condition2.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printB() { lock.lock(); try { //業務,判斷->執行->通知 while (number != 2) { //等待 condition2.await(); } System.out.println(Thread.currentThread().getName() + "=>BBBBB"); //通知指定的人,C number = 3; condition3.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void printC() { lock.lock(); try { //業務,判斷->執行->通知 while (number != 3) { //等待 condition3.await(); } System.out.println(Thread.currentThread().getName() + "=>CCCCC"); //通知指定的人,C number = 1; condition1.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } } ``` ## 3.八鎖現象 ```java package com.godfrey.lock8; import java.util.concurrent.TimeUnit; /** * description : 8鎖:關於鎖的8個問題 * 1.標準情況下 ,兩個執行緒先打印發簡訊還是打電話? 1/發簡訊 2/打電話 * 2.sendSms延時4秒 ,兩個執行緒先打印發簡訊還是打電話? 1/發簡訊 2/打電話 * * @author godfrey * @since 2020-05-15 */ public class Test1 { public static void main(String[] args) { Phone phone = new Phone(); new Thread(() -> { phone.sendSms(); }, "A").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { phone.call(); }, "B").start(); } } class Phone { //synchronized 鎖的物件是方法的呼叫者! public synchronized void sendSms() { try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("發簡訊"); } public synchronized void call() { System.out.println("打電話"); } } ``` ```java package com.godfrey.lock8; import java.util.concurrent.TimeUnit; /** * description : 8鎖:關於鎖的8個問題 * 3.增加了一個普通方法後!先執行發簡訊還是Hello? 普通方法 * 4.建立兩個物件,!先執行發簡訊還是打電話? 打電話 * * @author godfrey * @since 2020-05-15 */ public class Test2 { public static void main(String[] args) { //兩個物件,兩個呼叫者,兩把鎖 Phone2 phone1 = new Phone2(); Phone2 phone2 = new Phone2(); new Thread(() -> { phone1.sendSms(); }, "A").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { //phone1.hello(); phone2.call(); }, "B").start(); } } class Phone2 { //synchronized 鎖的物件是方法的呼叫者! public synchronized void sendSms() { try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("發簡訊"); } public synchronized void call() { System.out.println("打電話"); } //這裡沒有鎖!不是同步方法,不受鎖的影響 public void hello() { System.out.println("Hello"); } } ``` ```java package com.godfrey.lock8; import java.util.concurrent.TimeUnit; /** * description : 8鎖:關於鎖的8個問題 * 5.增加兩個靜態的同步方法,只要一個物件,先打樣發簡訊還是打電話? 發簡訊 * 6.兩個物件,增加兩個靜態的同步方法,只要一個物件,先打樣發簡訊還是打電話? 發簡訊 * * @author godfrey * @since 2020-05-15 */ public class Test3 { public static void main(String[] args) { //兩個物件,兩個呼叫者,兩把鎖 //static 靜態方法 //類一載入就有了!鎖的是class //Phone3 phone = new Phone3(); Phone3 phone1 = new Phone3(); Phone3 phone2 = new Phone3(); new Thread(() -> { //phone.sendSms(); phone1.sendSms(); }, "A").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { phone2.call(); }, "B").start(); } } class Phone3 { //synchronized 鎖的物件是方法的呼叫者! public static synchronized void sendSms() { try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("發簡訊"); } public static synchronized void call() { System.out.println("打電話"); } } ``` ```java package com.godfrey.lock8; import java.util.concurrent.TimeUnit; /** * description : 8鎖:關於鎖的8個問題 * 7.一個靜態同步方法一個普通方法,先打樣發簡訊還是打電話? 打電話 * 8.一個靜態同步方法一個普通方法,兩個物件,先打樣發簡訊還是打電話? 打電話 * * @author godfrey * @since 2020-05-15 */ public class Test4 { public static void main(String[] args) { //Phone4 phone = new Phone4(); Phone4 phone1 = new Phone4(); Phone4 phone2 = new Phone4(); new Thread(() -> { //phone.sendSms(); phone1.sendSms(); }, "A").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { phone2.call(); }, "B").start(); } } class Phone4 { //靜態同步方法,鎖的物件是Class模板! public static synchronized void sendSms() { try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("發簡訊"); } //普通同步方法,鎖的是呼叫者 public synchronized void call() { System.out.println("打電話"); } } ``` > 小結:看鎖的是Class還是物件,看是否同一個呼叫者 ## 4.集合類不安全 > List不安全 ```java package com.godfrey.unsafe; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; /** * description : java.util.ConcurrentModificationException 併發修改異常 * * @author godfrey * @since 2020-05-15 */ public class ListTest { public static void main(String[] args) { //併發下 ArrayList不安全的 /** * 解決方案: * 1.List list = new Vector<>(); * 2.List list = Collections.synchronizedList(new ArrayList<>()); * 3.List list = new CopyOnWriteArrayList<>(); */ //CopyOnWrite 寫入時複製COW 計算機程式設計 領域的一種優化策略 //多個執行緒呼叫的時候,list, 讀取的時候,固定的,寫入(覆蓋) //在寫入的時候避免覆蓋,造成資料問題! //讀寫分離 //CopyOnWriteArrayList 比 Vector 牛逼在哪裡?CopyOnWriteArrayList用Lock,Vector用Synchronized List list = new CopyOnWriteArrayList<>(); for (int i = 0; i < 10; i++) { new Thread(() -> { list.add(UUID.randomUUID().toString().substring(0, 5)); System.out.println(list); }, String.valueOf(i)).start(); } } } ``` > Set不安全 ```java package com.godfrey.unsafe; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArraySet; /** * description : java.util.ConcurrentModificationException 併發修改異常 * * @author godfrey * @since 2020-05-15 */ public class SetTest { public static void main(String[] args) { //HashSet set = new HashSet<>(); //併發下 HashSet不安全的 /** * 解決方案: * 1. Set set = Collections.synchronizedSet(new HashSet<>()); * 2. Set set = new CopyOnWriteArraySet<>(); */ Set set = new CopyOnWriteArraySet<>(); for (int i = 0; i < 100; i++) { new Thread(() -> { set.add(UUID.randomUUID().toString().substring(0, 5)); System.out.println(set); }, String.valueOf(i)).start(); } } } ``` 問:HashSet的底層是什麼? 答:HashMap ```java public HashSet() { map = new HashMap<>(); } //add set的本質是map key public boolean add(E e) { return map.put(e, PRESENT)==null; } private static final Object PRESENT = new Object(); ``` > Map不安全 ```java package com.godfrey.unsafe; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * description : java.util.ConcurrentModificationException 併發修改異常 * * @author godfrey * @since 2020-05-15 */ public class MapTest { public static void main(String[] args) { // Map map= new HashMap<>(); // 等價於 Map map = new HashMap<>(16,0.75f);//載入因子,初始化容量 //併發下 HashMap不安全的 /** * 解決方案: * 1.Map map = Collections.synchronizedMap(new HashMap<>()); * 2.Map map = new ConcurrentHashMap<>(); */ Map map = new ConcurrentHashMap<>(); for (int i = 0; i < 30; i++) { new Thread(() -> { map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5)); System.out.println(map); }, String.valueOf(i)).start(); } } } ``` ## 5.Callable ![](http://imgcloud.duiyi.xyz//data20200515152410.png) 1. 有返回值 2. 可以丟擲異常 3. 方法不同,run()/call() > 程式碼測試 ![](http://imgcloud.duiyi.xyz//data20200515153629.png). ![](http://imgcloud.duiyi.xyz//data20200515153755.png) ![](http://imgcloud.duiyi.xyz//data20200515154226.png) ```java package com.godfrey.callable; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * description : Callable測試 * * @author godfrey * @since 2020-05-15 */ public class CallableTest { public static void main(String[] args) throws ExecutionException, InterruptedException { //new Thread(new Runnable).start(); //new Thread(new FutureTask()).start(); //new Thread(new FutureTask(Callable)).start(); MyThread thread = new MyThread(); FutureTask futureTask = new FutureTask(thread);//適配類 new Thread(futureTask, "A").start(); new Thread(futureTask, "B").start();//結果會被快取,提高效率,最後列印只有一份 Integer integer = futureTask.get();//獲取Callable的返回結果(get方法可能會產生阻塞【大資料等待返回結果慢】!把它放到最會,或者用非同步通訊) System.out.println(integer); } } class MyThread implements Callable { @Override public Integer call() { System.out.println("call()"); return 1024; } } ``` 細節: 1. 有快取 2. get(),結果可能會等待,會阻塞 ## 6.常用輔助類(必會) ### 6.1 CountDownLatch ![](http://imgcloud.duiyi.xyz//data20200515160841.png) ```java package com.godfrey.add; import java.util.concurrent.CountDownLatch; /** * description : 減法計數器 * * @author godfrey * @since 2020-05-15 */ public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { //總數是6 CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + "\tGo Out"); countDownLatch.countDown();//-1 }, String.valueOf(i)).start(); } countDownLatch.await();//等待計數器歸零,然後再向下執行 System.out.println("Close Door"); } } ``` **原理:** `countDownLatch.countDown()` //數量-1 `countDownLatch.await()` //等待計數器歸零,然後再向下執行 每次有執行緒呼叫countDown()數量-1 , 假設計數器變為0 , countDownLatch.await()就會被喚醒,繼續執行! ### 6.2 CyclicBarrier ![](http://imgcloud.duiyi.xyz//data20200515162109.png) 加法計數器 ```java package com.godfrey.add; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * description : 加法計數器 * * @author godfrey * @since 2020-05-15 */ public class CyclicBarrierDemo { public static void main(String[] args) { /** * 集齊七顆龍珠召喚神龍 * 集齊龍珠的執行緒 */ CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> { System.out.println("召喚神龍成功"); }); for (int i = 0; i < 7; i++) { final int temp = i;//lambda操作不到i new Thread(() -> { System.out.println(Thread.currentThread().getName() + "收集" + temp + "個龍珠"); try { cyclicBarrier.await();//等待 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }, String.valueOf(i)).start(); } } } ``` ### 6.3 Semaphore Semaphore:訊號量 ![](http://imgcloud.duiyi.xyz//data20200515164354.png) 搶車位! ```java package com.godfrey.add; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * description : 訊號量 * * @author godfrey * @since 2020-05-15 */ public class SemaphoreDemo { public static void main(String[] args) { //執行緒數量:停車位! 限流! Semaphore semaphore = new Semaphore(3); for (int i = 0; i < 6; i++) { new Thread(() -> { //acquire() 得到 try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "搶到車位"); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName() + "離開車位"); } catch (InterruptedException e) { e.printStackTrace(); } finally { //release() 釋放 semaphore.release(); } }).start(); } } } ``` **原理:** `semaphore.acquire()` 獲得,假設如果已經滿了, 等待,等待被釋放為止! `semaphore.release()` 釋放,會將當前的訊號量釋放+ 1 ,然後喚醒等待的執行緒! 作用: 1. 多個共享資源互斥的使用! 2. 併發限流,控制最大的執行緒數! ## 7.讀寫鎖 ReadWriteLock ![](http://imgcloud.duiyi.xyz//data20200515170353.png) ```java package com.godfrey.rw; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * description : 讀寫鎖 * 獨佔鎖(寫鎖) 一次只能被一個執行緒佔有 * 共享鎖(讀鎖) 多個執行緒可以同時佔有 * ReadWriteLock * 讀-讀 可以共存! * 讀-寫 不能共存! * 寫-寫 不能共存! * * @author godfrey * @since 2020-05-15 */ public class ReadWriteLockDemo { public static void main(String[] args) { MyCacheLock myCache = new MyCacheLock(); //寫入 for (int i = 0; i < 10; i++) { final int temp = i; new Thread(() -> { myCache.put(temp + "", temp + ""); }, String.valueOf(i)).start(); } //讀取 for (int i = 0; i < 10; i++) { final int temp = i; new Thread(() -> { myCache.get(temp + ""); }, String.valueOf(i)).start(); } } } //加鎖的 class MyCacheLock { private volatile Map map = new HashMap<>(); //讀寫鎖,更加細粒度的控制 private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); // 存,寫入的時候,只希望同時只有一個執行緒寫 public void put(String key, Object value) { readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + "寫入" + key); map.put(key, value); System.out.println(Thread.currentThread().getName() + "寫入OK"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } // 取,讀,所有人都可以 public void get(String key) { readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "讀入" + key); Object o = map.get(key); System.out.println(Thread.currentThread().getName() + "讀入OK"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.readLock().unlock(); } } } /** * 自定義快取 */ class MyCache { private volatile Map map = new HashMap<>(); //存,寫 public void put(String key, Object value) { System.out.println(Thread.currentThread().getName() + "寫入" + key); map.put(key, value); System.out.println(Thread.currentThread().getName() + "寫入OK"); } //取,讀 public void get(String key) { System.out.println(Thread.currentThread().getName() + "讀入" + key); Object o = map.get(key); System.out.println(Thread.currentThread().getName() + "讀入OK"); } } ``` ## 8.阻塞佇列 ![](http://imgcloud.duiyi.xyz//data20200515185342.png) 阻塞佇列: ![](http://imgcloud.duiyi.xyz//data20200515191942.png) ![](http://imgcloud.duiyi.xyz//data20200515192054.png) ![](http://imgcloud.duiyi.xyz//data20200515202018.png) 什麼情況下我們會使用 阻塞佇列:多執行緒併發處理,執行緒池! **學會使用佇列** 新增、移除 **四組API** | 方式 | 丟擲異常 | 有返回值,不丟擲異常 | 阻塞 等待 | 超時 | | -------------- | -------- | -------------------- | --------- | ----- | | 新增 | add | offer | put | offer | | 移除 | remove | poll | take | poll | | 判斷佇列的首部 | element | peek | - | - | ```java /** * 丟擲異常 */ public static void test1() { ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.add("a")); System.out.println(blockingQueue.add("b")); System.out.println(blockingQueue.add("c")); //ava.lang.IllegalStateException: Queue full 丟擲異常!佇列已滿 //System.out.println(blockingQueue.add("d")); System.out.println(blockingQueue.element());//檢視隊首元素是誰 System.out.println("==================="); System.out.println(blockingQueue.remove()); System.out.println(blockingQueue.remove()); System.out.println(blockingQueue.remove()); //java.lang.IllegalStateException: Queue full 丟擲異常!佇列為空 //System.out.println(blockingQueue.remove()); } ``` ```java /** * 有返回值,沒有異常 */ public static void test2() { ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.offer("a")); System.out.println(blockingQueue.offer("b")); System.out.println(blockingQueue.offer("c")); //System.out.println(blockingQueue.offer("d"));// false 不丟擲異常! System.out.println(blockingQueue.peek());//檢視隊首元素是誰 System.out.println("==================="); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); //System.out.println(blockingQueue.remove());// null 不丟擲異常! } ``` ```java /** * 等待,阻塞(一直阻塞) */ public static void test3() throws InterruptedException { // 佇列的大小 ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3); // 一直阻塞 blockingQueue.put("a"); blockingQueue.put("b"); blockingQueue.put("c"); // blockingQueue.put("d"); // 佇列沒有位置了,一直阻塞 System.out.println(blockingQueue.take()); System.out.println(blockingQueue.take()); System.out.println(blockingQueue.take()); System.out.println(blockingQueue.take()); // 沒有這個元素,一直阻塞 } ``` ```java /** * 等待,阻塞(等待超市) */ public static void test4() throws InterruptedException { ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3); blockingQueue.offer("a"); blockingQueue.offer("b"); blockingQueue.offer("c"); // blockingQueue.offer("d",2,TimeUnit.SECONDS); // 等待超過2秒就退出 System.out.println("==============="); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); blockingQueue.poll(2, TimeUnit.SECONDS); // 等待超過2秒就退出 } ``` > SynchronousQueue 同步佇列 沒有容量, 進去一個元素,必須等待取出來之後,才能再往裡面放一個元素! put、take ```java package com.godfrey.bq; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; /** * description : * * @author godfrey * @since 2020-05-15 */ /** * 同步佇列 * 和其他的BlockingQueue 不一樣, SynchronousQueue 不儲存元素 * put了一個元素,必須從裡面先take取出來,否則不能在put進去值! */ public class SynchronousQueueDemo { public static void main(String[] args) { BlockingQueue blockingQueue = new SynchronousQueue<>(); // 同步佇列 new Thread(() -> { try { blockingQueue.put("1"); System.out.println(Thread.currentThread().getName() + " put 1"); blockingQueue.put("2"); System.out.println(Thread.currentThread().getName() + " put 2"); blockingQueue.put("3"); System.out.println(Thread.currentThread().getName() + " put 3"); } catch (InterruptedException e) { e.printStackTrace(); } }, "T1").start(); new Thread(() -> { try { TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take()); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take()); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); } }, "T2").start(); } } ``` ## 9.執行緒池(重點) 執行緒池:三大方法、7大引數、4種拒絕策略 > 池話技術 程式的執行,本質:佔用系統的資源! 優化資源的使用!=>池化技術 執行緒池、連線池、記憶體池、物件池///..... 建立、銷燬。十分浪費資源 池化技術:事先準備好一些資源,有人要用,就來我這裡拿,用完之後還給我 **執行緒池的好處:** 1. 降低資源的消耗 2. 提高響應的速度 3. 方便管理 ==**執行緒複用、可以控制最大併發數、管理執行緒**== > 三大方法 ![](http://imgcloud.duiyi.xyz//data20200515215358.png) ```java package com.godfrey.pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * description : Executors 工具類、3大方法 * * @author godfrey * @since 2020-05-15 */ public class Demo01 { public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor();// 單個執行緒 //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 建立一個固定的執行緒池的大小 //ExecutorService threadPool = Executors.newCachedThreadPool();// 可伸縮的,遇強則強,遇弱則弱 try { for (int i = 0; i < 100; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + "\tOK"); }); } } catch (Exception e) { e.printStackTrace(); } finally { // 執行緒池用完,程式結束,關閉執行緒池 threadPool.shutdown(); } } } ``` > 七大引數 原始碼分析: ```java public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue())); } public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue()); } //本質ThreadPoolExecutor() public ThreadPoolExecutor(int corePoolSize, // 核心執行緒池大小 int maximumPoolSize, // 最大核心執行緒池大小 long keepAliveTime, // 超時了沒有人呼叫就會釋放 TimeUnit unit, // 超時單位 BlockingQueue workQueue, // 阻塞佇列 ThreadFactory threadFactory, // 執行緒工廠:建立執行緒的,一般不用動 RejectedExecutionHandler handler // 拒絕策略) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; } ``` ![](http://imgcloud.duiyi.xyz//data20200515224657.png) ![](http://imgcloud.duiyi.xyz//data20200515224719.png) > 手寫一個執行緒池 ```java package com.godfrey.pool; import java.util.concurrent.*; /** * description : 七大引數與四種拒絕策略 * 四種拒絕策略: * AbortPolicy(預設):佇列滿了,還有任務進來,不處理這個任務的,直接丟擲 RejectedExecution異常! * CallerRunsPolicy:哪來的回哪裡! * DiscardOldestPolicy:佇列滿了,拋棄佇列中等待最久的任務,然後把當前任務加入佇列中嘗試再次提交 * DiscardPolicy():佇列滿了,直接丟棄任務,不予任何處理也不丟擲異常.如果允許任務丟失,這是最好的拒絕策略! * * @author godfrey * @since 2020-05-15 */ public class Demo02 { public static void main(String[] args) { ExecutorService threadPool = new ThreadPoolExecutor( //模擬銀行業務辦理 2, //常駐核心執行緒數 辦理業務視窗初始數量 5, //執行緒池能夠容納同時執行的最大執行緒數,此值大於等於1, 辦理業務視窗最大數量 3, //多餘的空閒執行緒存活時間,當空間時間達到keepAliveTime值時,多餘的執行緒會被銷燬直到只剩下corePoolSize個執行緒為止 釋放後窗口數量會變為常駐核心數 TimeUnit.SECONDS, //超時單位 new LinkedBlockingDeque<>(3), //任務佇列,被提交但尚未被執行的任務. 候客區座位數量 Executors.defaultThreadFactory(), //執行緒工廠:建立執行緒的,一般不用動 new ThreadPoolExecutor.DiscardOldestPolicy()); //拒絕策略,表示當執行緒佇列滿了並且工作執行緒大於等於執行緒池的最大顯示 數(maxnumPoolSize)時如何來拒絕 try { for (int i = 0; i < 10; i++) { threadPool.execute(() -> { System.out.println(Thread.currentThread().getName() + "\tOK"); }); } } catch (Exception e) { e.printStackTrace(); } finally { // 執行緒池用完,程式結束,關閉執行緒池 threadPool.shutdown(); } } } ``` > 四種拒絕策略 1. AbortPolicy(預設):佇列滿了,還有任務進來,不處理這個任務的,直接丟擲 RejectedExecution異常 2. CallerRunsPolicy:哪來的回哪裡! 3. DiscardOldestPolicy:佇列滿了,拋棄佇列中等待最久的任務,然後把當前任務加入佇列中嘗試再次提交 4. DiscardPolicy():佇列滿了,直接丟棄任務,不予任何處理也不丟擲異常.如果允許任務丟失,這是最好的拒絕策略! > 小結和拓展 池的最大的大小如何去設定! 獲取CPU核數`System.out.println(Runtime.getRuntime().availableProcessors())` 瞭解:用來(調優) - CPU密集型:CPU核數+1 - IO密集型: - CPU核數*2 - CPU核數/1.0-阻塞係數 阻塞係數在0.8~0.9之間 ## 10.四大函式式介面(必需掌握) 新時代的程式設計師:lambda表示式、鏈式程式設計、函式式介面、Stream流式計算 > 函式式介面:只有一個方法的介面 ```java @FunctionalInterface public interface Runnable { public abstract void run(); } ``` ![](http://imgcloud.duiyi.xyz//data20200515235259.png). 程式碼測試 > 函式式介面 ![](http://imgcloud.duiyi.xyz//data20200516000920.png)。 ```java package com.godfrey.function; import java.util.function.Function; /** * description : Function 函式式介面,有一個輸入引數,有一個輸出 * 只要是 函式型介面 可以 用 lambda表示式簡化 * * @author godfrey * @since 2020-05-16 */ public class Demo01 { public static void main(String[] args) { //Function function = new Function(){ // @Override // public String apply(String o) { // return o; // } //}; Function function = str->{return str;}; System.out.println(function.apply("123")); } } ``` > 斷定型介面:有一個輸入引數,返回值只能是 布林值! ![](http://imgcloud.duiyi.xyz//data20200516003834.png). ```java package com.godfrey.function; import java.util.function.Predicate; /** * description : 斷定型介面,有一個輸入引數,返回值只能是布林值! * * @author godfrey * @since 2020-05-16 */ public class Demo02 { public static void main(String[] args) { //判斷字串是否為空 //Predicate predicate = new Predicate() { // @Override // public boolean test(String str) { // return str.isEmpty(); // } //}; Predicate predicate = str -> { return str.isEmpty(); }; System.out.println(predicate.test("")); } } ``` > Consumer 消費型介面 ![](http://imgcloud.duiyi.xyz//data20200516004312.png). ```java package com.godfrey.function; import java.util.function.Consumer; /** * description : Consumer 消費型介面,只有輸入,沒有返回值 * * @author godfrey * @since 2020-05-16 */ public class Demo03 { public static void main(String[] args) { //Consumer consumer = new Consumer() { // @Override // public void accept(String str) { // System.out.println(str); // } //}; Consumer consumer = str -> System.out.println(str); consumer.accept("godfrey"); } } ``` > Supplier 供給型介面 ![](http://imgcloud.duiyi.xyz//data20200516004933.png). ```java package com.godfrey.function; import java.util.function.Supplier; /** * description : Supplier 供給型介面,沒有引數,只有返回值 * * @author godfrey * @since 2020-05-16 */ public class Demo04 { public static void main(String[] args) { //Supplier supplier = new Supplier() { // @Override // public Integer get() { // System.out.println("get()"); // return 1024; // } //}; Supplier supplier = () -> { return 1024;}; System.out.println(supplier.get()); } } ``` ## 11.Stream流式計算 > 什麼是Stream流式計算 大資料:儲存 + 計算 集合、MySQL 本質就是儲存東西的; 計算都應該交給流來操作! ![](http://imgcloud.duiyi.xyz//data20200516095630.png). ```java package com.godfrey.stream; import java.util.Arrays; import java.util.List; /** * description :一分鐘內完成此題,只能用一行程式碼實現! * 現在有5個使用者!篩選: * 1、ID 必須是偶數 * 2、年齡必須大於23歲 * 3、使用者名稱轉為大寫字母 * 4、使用者名稱字母倒著排序 * 5、只輸出一個使用者! * * @author godfrey * @since 2020-05-16 */ public class Test { public static void main(String[] args) { User u1 = new User(1, "a", 21); User u2 = new User(2, "b", 22); User u3 = new User(3, "c", 23); User u4 = new User(4, "d", 24); User u5 = new User(6, "e", 25); //集合就算儲存 List list = Arrays.asList(u1, u2, u3, u4, u5); //計算交給Stream流 list.stream() .filter(u -> { return u.getId() % 2 == 0; }) .filter(u->{return u.getAge()>23;}) .map(u->{return u.getName().toUpperCase();}) .sorted((uu1,uu2)->{return uu2.compareTo(uu1);}) .limit(1) .forEach(System.out::println); } } ``` ## 12.ForkJoin > 什麼是 ForkJoin ForkJoin 在 JDK 1.7 , 並行執行任務!提高效率。大資料量! 大資料:Map Reduce (把大任務拆分為小任務) ![](http://imgcloud.duiyi.xyz//data20200516100134.png) > ForkJoin 特點:工作竊取 這個裡面維護的都是雙端佇列 ![](http://imgcloud.duiyi.xyz//data20200516100358.png). > Forkjoin ![](http://imgcloud.duiyi.xyz//data20200516104234.png). ![](http://imgcloud.duiyi.xyz//data20200516104401.png) ```java package com.godfrey.forkjoin; import java.util.concurrent.RecursiveTask; /** * 求和計算的任務! * 如何使用 forkjoin * 1、forkjoinPool 通過它來執行 * 2、計算任務 forkjoinPool.execute(ForkJoinTask task) * 3、 計算類要繼承 ForkJoinTask * * @author godfrey * @since 2020-05-16 */ public class ForkJoinDemo extends RecursiveTask { private Long start; private Long end; //臨界值 private Long temp = 10000L; public ForkJoinDemo(Long start, Long end) { this.start = start; this.end = end; } //計算方法 @Override protected Long compute() { if ((end - start) > temp) { Long sum = 0L; for (Long i = start; i < end; i++) { sum += i; } return sum; } else { // forkjoin 遞迴 Long middle = (start + end) / 2;//中間值 ForkJoinDemo task1 = new ForkJoinDemo(start, middle); task1.fork(); // 拆分任務,把任務壓入執行緒佇列 ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end); task2.fork(); // 拆分任務,把任務壓入執行緒佇列 return task1.join() + task2.join(); } } } ``` 測試: ```java package com.godfrey.forkjoin; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.stream.LongStream; /** * description : 效率測試 * * @author godfrey * @since 2020-05-16 */ public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { //test1(); //sum=499999999500000000 時間:7192 //test2(); //sum=499999999500000000 時間:6949 test3(); //sum=500000000500000000 時間:526 } // 普通程式設計師 public static void test1() { Long sum = 0L; Long start = System.currentTimeMillis(); for (Long i = 0L; i < 10_0000_0000L; i++) { sum += i; } Long end = System.currentTimeMillis(); System.out.println("sum=" + sum + " 時間:" + (end - start)); } //ForkJoin public static void test2() throws ExecutionException, InterruptedException { Long start = System.currentTimeMillis(); ForkJoinPool forkJoinPool = new ForkJoinPool(); ForkJoinTask task = new ForkJoinDemo(0L, 10_0000_0000L); ForkJoinTask submit = forkJoinPool.submit(task); Long sum = submit.get(); Long end = System.currentTimeMillis(); System.out.println("sum=" + sum + " 時間:" + (end - start)); } //Stream並行流 public static void test3() { Long start = System.currentTimeMillis(); Long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum); Long end = System.currentTimeMillis(); System.out.println("sum=" + sum + " 時間:" + (end - start)); } } ``` ## 13.非同步回撥 > Future 設計的初衷: 對將來的某個事件的結果進行建模 ![](http://imgcloud.duiyi.xyz//data20200516111155.png) ```java package com.godfrey.future; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * description : 非同步回撥 * * @author godfrey * @since 2020-05-16 */ public class Demo01 { public static void main(String[] args) throws ExecutionException, InterruptedException { //test1(); test02(); } // 沒有返回值的 runAsync 非同步回撥 public static void test1() throws InterruptedException, ExecutionException { CompletableFuture completableFuture = CompletableFuture.runAsync(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "runAsync=>Void"); }); System.out.println("1111"); completableFuture.get(); // 獲取阻塞執行結果 } // 有返回值的 supplyAsync 非同步回撥 // ajax,成功和失敗的回撥 // 返回的是錯誤資訊; public static void test02() throws InterruptedException, ExecutionException { CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer"); int i = 10 / 0; return 1024; }); System.out.println(completableFuture.whenComplete((t, u) -> { System.out.println("t=>" + t); // 正常的返回結果 System.out.println("u=>" + u); // 錯誤資訊:java.util.concurrent.CompletionException:java.lang.ArithmeticException: / by zero }).exceptionally((e) -> { System.out.println(e.getMessage()); return 233; // 可以獲取到錯誤的返回結果 }).get()); /** * succee Code 200 * error Code 404 500 */} } ``` ## 14.JMM > 請你談談你對 Volatile 的理解 Volatile 是 Java 虛擬機器提供輕量級的同步機制 1. 保證可見性 2. ==不保證原子性== 3. 禁止指令重排 > 什麼是JMM JMM : Java記憶體模型,不存在的東西,概念!約定! **關於JMM的一些同步的約定:** 1. 執行緒解鎖前,必須把共享變數==立刻==刷回主存 2. 執行緒加鎖前,必須讀取主存中的最新值到工作記憶體中! 3. 加鎖和解鎖是同一把鎖 執行緒 **工作記憶體 、主記憶體** **8種操作:** ![](http://imgcloud.duiyi.xyz//data20200516114621.png) ![](http://imgcloud.duiyi.xyz//data20200516114655.png) **記憶體互動操作有8種,虛擬機器實現必須保證每一個操作都是原子的,不可再分的(對於double和long類** **型的變數來說,load、store、read和write操作在某些平臺上允許例外)** - lock (鎖定):作用於主記憶體的變數,把一個變數標識為執行緒獨佔狀態 - unlock (解鎖):作用於主記憶體的變數,它把一個處於鎖定狀態的變數釋放出來,釋放後的變數才可以被其他執行緒鎖定 - read (讀取):作用於主記憶體變數,它把一個變數的值從主記憶體傳輸到執行緒的工作記憶體中,以便隨後的load動作使用 - load (載入):作用於工作記憶體的變數,它把read操作從主存中變數放入工作記憶體中 - use (使用):作用於工作記憶體中的變數,它把工作記憶體中的變數傳輸給執行引擎,每當虛擬機器遇到一個需要使用到變數的值,就會使用到這個指令 - assign (賦值):作用於工作記憶體中的變數,它把一個從執行引擎中接受到的值放入工作記憶體的變數副本中 - store (儲存):作用於主記憶體中的變數,它把一個從工作記憶體中一個變數的值傳送到主記憶體中,以便後續的write使用 - write (寫入):作用於主記憶體中的變數,它把store操作從工作記憶體中得到的變數的值放入主記憶體的變數中 **JMM對這八種指令的使用,制定瞭如下規則:** - 不允許read和load、store和write操作之一單獨出現。即使用了read必須load,使用了store必須write - 不允許執行緒丟棄他最近的assign操作,即工作變數的資料改變了之後,必須告知主存 - 不允許一個執行緒將沒有assign的資料從工作記憶體同步回主記憶體 - 一個新的變數必須在主記憶體中誕生,不允許工作記憶體直接使用一個未被初始化的變數。就是懟變數 實施use、store操作之前,必須經過assign和load操作 - 一個變數同一時間只有一個執行緒能對其進行lock。多次lock後,必須執行相同次數的unlock才能解鎖 - 如果對一個變數進行lock操作,會清空所有工作記憶體中此變數的值,在執行引擎使用這個變數前,必須重新load或assign操作初始化變數的值 - 如果一個變數沒有被lock,就不能對其進行unlock操作。也不能unlock一個被其他執行緒鎖住的變數 - 對一個變數進行unlock操作之前,必須把此變數同步回主記憶體 ## 15.Volatile > 1.保證可見性 ```java package com.godfrey.tvolatile; import java.util.concurrent.TimeUnit; /** * description : volatile 保證可見性 * * @author godfrey * @since 2020-05-16 */ public class JMMDemo { // 不加 volatile 程式就會死迴圈! // 加 volatile 可以保證可見性 private volatile static int num = 0; public static void main(String[] args) { // main new Thread(() -> { // 執行緒 1 對主記憶體的變化不知道的 while (num == 0) { } }).start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } num = 1; System.out.println(num); } } ``` > 2.不保證原子性 原子性 : 不可分割 執行緒A在執行任務的時候,不能被打擾的,也不能被分割。要麼同時成功,要麼同時失敗 ```java package com.godfrey.tvolatile; /** * description : volatile 不保證原子性 * * @author godfrey * @since 2020-05-16 */ public class JMMDemo { private volatile static int num = 0; public static void add() { num++; } public static void main(String[] args) { //理論上num結果應該為 2 萬 for (int i = 0; i < 20; i++) { new Thread(() -> { for (int j = 0; j < 1000; j++) { add(); } }).start(); } while (Thread.activeCount() > 2) { // main gc Thread.yield(); } System.out.println(Thread.currentThread().getName() + " " + num); } } ``` **如果不加 lock 和 synchronized ,怎麼樣保證原子性** ![](http://imgcloud.duiyi.xyz//data20200516174823.png) 使用原子類,解決原子性問題 ![](http://imgcloud.duiyi.xyz//data20200516175025.png). ```java package com.godfrey.tvolatile; import java.util.concurrent.atomic.AtomicInteger; /** * description : volatile 不保證原子性 * * @author godfrey * @since 2020-05-16 */ public class VDemo02 { // volatile 不保證原子性 // 原子類的 Integer private volatile static AtomicInteger num = new AtomicInteger(); public static void add() { // num++; // 不是一個原子性操作 num.getAndIncrement(); // AtomicInteger + 1 方法, CAS } public static void main(String[] args) { //理論上num結果應該為 2 萬 for (int i = 0; i < 20; i++) { new Thread(() -> { for (int j = 0; j < 1000; j++) { add(); } }).start(); } while (Thread.activeCount() > 2) { // main gc Thread.yield(); } System.out.println(Thread.currentThread().getName() + " " + num); } } ``` 這些類的底層都直接和作業系統掛鉤!在記憶體中修改值!Unsafe類是一個很特殊的存在! > 指令重排 什麼是 指令重排:你寫的程式,**計算機並不是按照你寫的那樣去執行的** 原始碼-->編譯器優化的重排--> 指令並行也可能會重排--> 記憶體系統也會重排---> 執行 **==處理器在進行指令重排的時候,考慮:資料之間的依賴性!==** ```java int x = 1; // 1 int y = 2; // 2 x = x + 5; // 3 y = x * x; // 4 我們所期望的:1234 但是可能執行的時候回變成 2134 1324 可不可能是 4123! ``` 可能造成影響的結果: a b x y 這四個值預設都是 0; | 執行緒A | 執行緒B | | ----- | ----- | | x=a | y=b | | b=1 | a=2 | 正常的結果: x = 0;y = 0;但是可能由於指令重排 | 執行緒A | 執行緒B | | ----- | ----- | | b=1 | a=2 | | x=a | y=b | 指令重排導致的詭異結果: x = 2;y = 1; > 禁止指令重排 **volatile可以禁止指令重排:** 記憶體屏障。CPU指令。作用: 1. 保證特定的操作的執行順序! 2. 可以保證某些變數的記憶體可見性 (利用這些特性volatile實現了可見性) ![](http://imgcloud.duiyi.xyz//data20200516181146.png). **Volatile 是可以保持 可見性。不能保證原子性,由於記憶體屏障,可以保證避免指令重排的現象產生!** ## 16.徹底玩轉單例模式 餓漢式 DCL懶漢式,深究! > 餓漢式 ```java package com.godfrey.single; /** * description : 餓漢式單例 * * @author godfrey * @since 2020-05-16 */ public class Hungry { private Hungry() { } public final static Hungry HUNGRY = new Hungry(); public static Hungry getInstance() { return HUNGRY; } } ``` > 靜態內部類 ```java package com.godfrey.single; /** * description : 靜態內部類單例 * * @author godfrey * @since 2020-05-16 */ public class Holder { private Holder() { } private static class InnerClass { private final static Holder HOLDER = new Holder(); } public static Holder getInstance() { return InnerClass.HOLDER; } } ``` > 單例不安全,反射 > 列舉 ```java package com.godfrey.single; /** * description : 列舉單例 * * @author godfrey * @since 2020-05-16 */ public enum EnumSingle { INSTANCE; } ``` 通過class檔案反編譯得到Java檔案: ![](http://imgcloud.duiyi.xyz//data20200516202300.png) ```java // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: EnumSingle.java package com.godfrey.single; import java.io.PrintStream; public final class EnumSingle extends Enum { public static EnumSingle[] values() { return (EnumSingle[])$VALUES.clone(); } public static EnumSingle valueOf(String name) { return (EnumSingle)Enum.valueOf(com/godfrey/single/EnumSingle, name); } private EnumSingle(String s, int i) { super(s, i); } public static void main(String args[]) { System.out.println(INSTANCE); } public static final EnumSingle INSTANCE; private static final EnumSingle $VALUES[]; static { INSTANCE = new EnumSingle("INSTANCE", 0); $VALUES = (new EnumSingle[] { INSTANCE }); } } ``` 可以發現列舉的單例構造器是==有參==的 ## 17.深入理解CAS > 什麼是 CAS ```java package com.godfrey.cas; import java.util.concurrent.atomic.AtomicInteger; /** * description : CAS compareAndSet : 比較並交換 * * @author godfrey * @since 2020-05-16 */ public class CASDemo { public static void main(String[] args) { AtomicInteger atomicInteger = new AtomicInteger(2020); // 期望、更新 // public final boolean compareAndSet(int expectedValue, int newValue) // 如果我期望的值達到了,那麼就更新,否則,就不更新, CAS 是CPU的併發原語! System.out.println(atomicInteger.compareAndSet(2020, 2021)); System.out.println(atomicInteger.get()); atomicInteger.getAndIncrement(); System.out.println(atomicInteger.compareAndSet(2020, 2021)); System.out.println(atomicInteger.get()); } } ``` > Unsafe 類 ![](http://imgcloud.duiyi.xyz//data20200516204302.png) ![](http://imgcloud.duiyi.xyz//data20200516204348.png) ![](http://imgcloud.duiyi.xyz//data20200516204619.png) CAS : 比較當前工作記憶體中的值和主記憶體中的值,如果這個值是期望的,那麼則執行操作!如果不是就一直迴圈! **缺點:** 1. 迴圈會耗時 2. 一次性只能保證一個共享變數的原子性 3. ABA問題 > CAS : ABA 問題(狸貓換太子) ![](http://imgcloud.duiyi.xyz//data20200516204901.png) ```java package com.godfrey.cas; import java.util.concurrent.atomic.AtomicInteger; /** * description : CAS問題:ABA(狸貓換太子) * * @author godfrey * @since 2020-05-16 */ public class ABADemo { // CAS compareAndSet : 比較並交換! public static void main(String[] args) { AtomicInteger atomicInteger = new AtomicInteger(2020); // 期望、更新 // public final boolean compareAndSet(int expect, int update) // 如果我期望的值達到了,那麼就更新,否則,就不更新, CAS 是CPU的併發原語! // ============== 搗亂的執行緒 ================== System.out.println(atomicInteger.compareAndSet(2020, 2021)); System.out.println(atomicInteger.get()); System.out.println(atomicInteger.compareAndSet(2021, 2020)); System.out.println(atomicInteger.get()); // ============== 期望的執行緒 ================== System.out.println(atomicInteger.compareAndSet(2020, 6666)); System.out.println(atomicInteger.get()); } } ``` ## 18.原子引用 > 解決ABA 問題,引入原子引用! 對應的思想:樂觀鎖 帶版本號 的原子操作! ```java package com.godfrey.cas; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicStampedReference; /** * description : 原子引用解決ABA問題 * * @author godfrey * @since 2020-05-16 */ public class AtomicStampedReferenceDemo { //AtomicStampedReference 注意,如果泛型是一個包裝類,注意物件的引用問題 static AtomicStampedReference atomicStampedReference = new AtomicStampedReference<>(1, 1); public static void main(String[] args) { new Thread(() -> { int stamp = atomicStampedReference.getStamp(); // 獲得版本號 Syste