自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

求求你,別再用Wait和Notify了!

開發(fā) 前端
Condition 是 JDK 1.5 中提供的用來替代 wait 和 notify 的線程通訊方法,那么一定會有人問:為什么不能用 wait 和 notify 了? 哥們我用的好好的。老弟別著急,聽我給你細說...

[[357664]]

Condition 是 JDK 1.5 中提供的用來替代 wait 和 notify 的線程通訊方法,那么一定會有人問:為什么不能用 wait 和 notify 了? 哥們我用的好好的。老弟別著急,聽我給你細說...

之所以推薦使用 Condition 而非 Object 中的 wait 和 notify 的原因有兩個:

  1. 使用 notify 在極端環(huán)境下會造成線程“假死”;
  2. Condition 性能更高。

接下來怎們就用代碼和流程圖的方式來演示上述的兩種情況。

1.notify 線程“假死”

所謂的線程“假死”是指,在使用 notify 喚醒多個等待的線程時,卻意外的喚醒了一個沒有“準(zhǔn)備好”的線程,從而導(dǎo)致整個程序進入了阻塞的狀態(tài)不能繼續(xù)執(zhí)行。

以多線程編程中的經(jīng)典案例生產(chǎn)者和消費者模型為例,我們先來演示一下線程“假死”的問題。

1.1 正常版本

在演示線程“假死”的問題之前,我們先使用 wait 和 notify 來實現(xiàn)一個簡單的生產(chǎn)者和消費者模型,為了讓代碼更直觀,我這里寫一個超級簡單的實現(xiàn)版本。我們先來創(chuàng)建一個工廠類,工廠類里面包含兩個方法,一個是循環(huán)生產(chǎn)數(shù)據(jù)的(存入)方法,另一個是循環(huán)消費數(shù)據(jù)的(取出)方法,實現(xiàn)代碼如下。

  1. /** 
  2.  * 工廠類,消費者和生產(chǎn)者通過調(diào)用工廠類實現(xiàn)生產(chǎn)/消費 
  3.  */ 
  4. class Factory { 
  5.     private int[] items = new int[1]; // 數(shù)據(jù)存儲容器(為了演示方便,設(shè)置容量最多存儲 1 個元素) 
  6.     private int size = 0;             // 實際存儲大小 
  7.  
  8.     /** 
  9.      * 生產(chǎn)方法 
  10.      */ 
  11.     public synchronized void put() throws InterruptedException { 
  12.         // 循環(huán)生產(chǎn)數(shù)據(jù) 
  13.         do { 
  14.             while (size == items.length) { // 注意不能是 if 判斷 
  15.                 // 存儲的容量已經(jīng)滿了,阻塞等待消費者消費之后喚醒 
  16.                 System.out.println(Thread.currentThread().getName() + " 進入阻塞"); 
  17.                 this.wait(); 
  18.                 System.out.println(Thread.currentThread().getName() + " 被喚醒"); 
  19.             } 
  20.             System.out.println(Thread.currentThread().getName() + " 開始工作"); 
  21.             items[0] = 1; // 為了方便演示,設(shè)置固定值 
  22.             size++; 
  23.             System.out.println(Thread.currentThread().getName() + " 完成工作"); 
  24.             // 當(dāng)生產(chǎn)隊列有數(shù)據(jù)之后通知喚醒消費者 
  25.             this.notify(); 
  26.  
  27.         } while (true); 
  28.     } 
  29.  
  30.     /** 
  31.      * 消費方法 
  32.      */ 
  33.     public synchronized void take() throws InterruptedException { 
  34.         // 循環(huán)消費數(shù)據(jù) 
  35.         do { 
  36.             while (size == 0) { 
  37.                 // 生產(chǎn)者沒有數(shù)據(jù),阻塞等待 
  38.                 System.out.println(Thread.currentThread().getName() + " 進入阻塞(消費者)"); 
  39.                 this.wait(); 
  40.                 System.out.println(Thread.currentThread().getName() + " 被喚醒(消費者)"); 
  41.             } 
  42.             System.out.println("消費者工作~"); 
  43.             size--; 
  44.             // 喚醒生產(chǎn)者可以添加生產(chǎn)了 
  45.             this.notify(); 
  46.         } while (true); 
  47.     } 

接下來我們來創(chuàng)建兩個線程,一個是生產(chǎn)者調(diào)用 put 方法,另一個是消費者調(diào)用 take 方法,實現(xiàn)代碼如下:

  1. public class NotifyDemo { 
  2.     public static void main(String[] args) { 
  3.         // 創(chuàng)建工廠類 
  4.         Factory factory = new Factory(); 
  5.  
  6.         // 生產(chǎn)者 
  7.         Thread producer = new Thread(() -> { 
  8.             try { 
  9.                 factory.put(); 
  10.             } catch (InterruptedException e) { 
  11.                 e.printStackTrace(); 
  12.             } 
  13.         }, "生產(chǎn)者"); 
  14.         producer.start(); 
  15.  
  16.         // 消費者 
  17.         Thread consumer = new Thread(() -> { 
  18.             try { 
  19.                 factory.take(); 
  20.             } catch (InterruptedException e) { 
  21.                 e.printStackTrace(); 
  22.             } 
  23.         }, "消費者"); 
  24.         consumer.start(); 
  25.     } 

執(zhí)行結(jié)果如下:


從上述結(jié)果可以看出,生產(chǎn)者和消費者在循環(huán)交替的執(zhí)行任務(wù),場面非常和諧,是我們想要的正確結(jié)果。

1.2 線程“假死”版本

當(dāng)只有一個生產(chǎn)者和一個消費者時,wait 和 notify 方法不會有任何問題,然而**將生產(chǎn)者增加到兩個時就會出現(xiàn)線程“假死”的問題了,**程序的實現(xiàn)代碼如下:

  1. public class NotifyDemo { 
  2.     public static void main(String[] args) { 
  3.   // 創(chuàng)建工廠方法(工廠類的代碼不變,這里不再復(fù)述) 
  4.         Factory factory = new Factory(); 
  5.  
  6.         // 生產(chǎn)者 
  7.         Thread producer = new Thread(() -> { 
  8.             try { 
  9.                 factory.put(); 
  10.             } catch (InterruptedException e) { 
  11.                 e.printStackTrace(); 
  12.             } 
  13.         }, "生產(chǎn)者"); 
  14.         producer.start(); 
  15.  
  16.         // 生產(chǎn)者 2 
  17.         Thread producer2 = new Thread(() -> { 
  18.             try { 
  19.                 factory.put(); 
  20.             } catch (InterruptedException e) { 
  21.                 e.printStackTrace(); 
  22.             } 
  23.         }, "生產(chǎn)者2"); 
  24.         producer2.start(); 
  25.          
  26.         // 消費者 
  27.         Thread consumer = new Thread(() -> { 
  28.             try { 
  29.                 factory.take(); 
  30.             } catch (InterruptedException e) { 
  31.                 e.printStackTrace(); 
  32.             } 
  33.         }, "消費者"); 
  34.         consumer.start(); 
  35.     } 

程序執(zhí)行結(jié)果如下:


從以上結(jié)果可以看出,當(dāng)我們將生產(chǎn)者的數(shù)量增加到 2 個時,就會造成線程“假死”阻塞執(zhí)行的問題,當(dāng)生產(chǎn)者 2 被喚醒又被阻塞之后,整個程序就不能繼續(xù)執(zhí)行了。

線程“假死”問題分析

我們先把以上程序的執(zhí)行步驟標(biāo)注一下,得到如下結(jié)果:


從上圖可以看出:當(dāng)執(zhí)行到第 ④ 步時,此時生產(chǎn)者為工作狀態(tài),而生產(chǎn)者 2 和消費者為等待狀態(tài),此時正確的做法應(yīng)該是喚醒消費著進行消費,然后消費者消費完之后再喚醒生產(chǎn)者繼續(xù)工作;但此時生產(chǎn)者卻錯誤的喚醒了生產(chǎn)者 2,而生產(chǎn)者 2 因為隊列已經(jīng)滿了,所以自身并不具備繼續(xù)執(zhí)行的能力,因此就導(dǎo)致了整個程序的阻塞,流程圖如下所示:

正確執(zhí)行流程應(yīng)該是這樣的:


1.3 使用 Condition

為了解決線程的“假死”問題,我們可以使用 Condition 來嘗試實現(xiàn)一下,Condition 是 JUC(java.util.concurrent)包下的類,需要使用 Lock 鎖來創(chuàng)建,Condition 提供了 3 個重要的方法:

  • await:對應(yīng) wait 方法;
  • signal:對應(yīng) notify 方法;
  • signalAll: notifyAll 方法。

Condition 的使用和 wait/notify 類似,也是先獲得鎖然后在鎖中進行等待和喚醒操作,Condition 的基礎(chǔ)用法如下:

  1. // 創(chuàng)建 Condition 對象 
  2. Lock lock = new ReentrantLock(); 
  3. Condition condition = lock.newCondition(); 
  4. // 加鎖 
  5. lock.lock(); 
  6. try { 
  7.     // 業(yè)務(wù)方法.... 
  8.      
  9.     // 1.進入等待狀態(tài) 
  10.     condition.await(); 
  11.  
  12.     // 2.喚醒操作 
  13.     condition.signal(); 
  14. } catch (InterruptedException e) { 
  15.     e.printStackTrace(); 
  16. } finally { 
  17.     lock.unlock(); 

小知識:Lock的正確使用姿勢

切記 Lock 的 lock.lock() 方法不能放入 try 代碼中,如果 lock 方法在 try 代碼塊之內(nèi),可能由于其它方法拋出異常,導(dǎo)致在 finally 代碼塊中, unlock 對未加鎖的對象解鎖,它會調(diào)用 AQS 的 tryRelease 方法(取決于具體實現(xiàn)類),拋出 IllegalMonitorStateException 異常。

回歸主題

回到本文的主題,我們?nèi)绻褂?Condition 來實現(xiàn)線程的通訊就可以避免程序的“假死”情況,因為 Condition 可以創(chuàng)建多個等待集,以本文的生產(chǎn)者和消費者模型為例,我們可以使用兩個等待集,一個用做消費者的等待和喚醒,另一個用來喚醒生產(chǎn)者,這樣就不會出現(xiàn)生產(chǎn)者喚醒生產(chǎn)者的情況了(生產(chǎn)者只能喚醒消費者,消費者只能喚醒生產(chǎn)者)這樣整個流程就不會“假死”了,它的執(zhí)行流程如下圖所示:


了解了它的基本流程之后,咱們來看具體的實現(xiàn)代碼。

基于 Condition 的工廠實現(xiàn)代碼如下:

  1. class FactoryByCondition { 
  2.     private int[] items = new int[1]; // 數(shù)據(jù)存儲容器(為了演示方便,設(shè)置容量最多存儲 1 個元素) 
  3.     private int size = 0;             // 實際存儲大小 
  4.     // 創(chuàng)建 Condition 對象 
  5.     private Lock lock = new ReentrantLock(); 
  6.     // 生產(chǎn)者的 Condition 對象 
  7.     private Condition producerCondition = lock.newCondition(); 
  8.     // 消費者的 Condition 對象 
  9.     private Condition consumerCondition = lock.newCondition(); 
  10.  
  11.     /** 
  12.      * 生產(chǎn)方法 
  13.      */ 
  14.     public void put() throws InterruptedException { 
  15.         // 循環(huán)生產(chǎn)數(shù)據(jù) 
  16.         do { 
  17.             lock.lock(); 
  18.             while (size == items.length) { // 注意不能是 if 判斷 
  19.                 // 生產(chǎn)者進入等待 
  20.                 System.out.println(Thread.currentThread().getName() + " 進入阻塞"); 
  21.                 producerCondition.await(); 
  22.                 System.out.println(Thread.currentThread().getName() + " 被喚醒"); 
  23.             } 
  24.             System.out.println(Thread.currentThread().getName() + " 開始工作"); 
  25.             items[0] = 1; // 為了方便演示,設(shè)置固定值 
  26.             size++; 
  27.             System.out.println(Thread.currentThread().getName() + " 完成工作"); 
  28.             // 喚醒消費者 
  29.             consumerCondition.signal(); 
  30.             try { 
  31.             } finally { 
  32.                 lock.unlock(); 
  33.             } 
  34.         } while (true); 
  35.     } 
  36.  
  37.     /** 
  38.      * 消費方法 
  39.      */ 
  40.     public void take() throws InterruptedException { 
  41.         // 循環(huán)消費數(shù)據(jù) 
  42.         do { 
  43.             lock.lock(); 
  44.             while (size == 0) { 
  45.                 // 消費者阻塞等待 
  46.                 consumerCondition.await(); 
  47.             } 
  48.             System.out.println("消費者工作~"); 
  49.             size--; 
  50.             // 喚醒生產(chǎn)者 
  51.             producerCondition.signal(); 
  52.             try { 
  53.             } finally { 
  54.                 lock.unlock(); 
  55.             } 
  56.         } while (true); 
  57.     } 

兩個生產(chǎn)者和一個消費者的實現(xiàn)代碼如下:

  1. public class NotifyDemo { 
  2.     public static void main(String[] args) { 
  3.         FactoryByCondition factory = new FactoryByCondition(); 
  4.  
  5.         // 生產(chǎn)者 
  6.         Thread producer = new Thread(() -> { 
  7.             try { 
  8.                 factory.put(); 
  9.             } catch (InterruptedException e) { 
  10.                 e.printStackTrace(); 
  11.             } 
  12.         }, "生產(chǎn)者"); 
  13.         producer.start(); 
  14.  
  15.         // 生產(chǎn)者 2 
  16.         Thread producer2 = new Thread(() -> { 
  17.             try { 
  18.                 factory.put(); 
  19.             } catch (InterruptedException e) { 
  20.                 e.printStackTrace(); 
  21.             } 
  22.         }, "生產(chǎn)者2"); 
  23.         producer2.start(); 
  24.  
  25.         // 消費者 
  26.         Thread consumer = new Thread(() -> { 
  27.             try { 
  28.                 factory.take(); 
  29.             } catch (InterruptedException e) { 
  30.                 e.printStackTrace(); 
  31.             } 
  32.         }, "消費者"); 
  33.         consumer.start(); 
  34.     } 

程序的執(zhí)行結(jié)果如下圖所示:


從上述結(jié)果可以看出,當(dāng)使用 Condition 時,生產(chǎn)者、消費者、生產(chǎn)者 2 會一直交替循環(huán)執(zhí)行,執(zhí)行結(jié)果符合我們的預(yù)期。

2.性能問題

在上面我們演示 notify 會造成線程的“假死”問題的時候,一定有朋友會想到,如果把 notify 換成 notifyAll 線程就不會“假死”了。

這樣做法確實可以解決線程“假死”的問題,但同時會到來新的性能問題,空說無憑,直接上代碼展示。

以下是使用 wait 和 notifyAll 改進后的代碼:

  1. /** 
  2.  * 工廠類,消費者和生產(chǎn)者通過調(diào)用工廠類實現(xiàn)生產(chǎn)/消費功能. 
  3.  */ 
  4. class Factory { 
  5.     private int[] items = new int[1];   // 數(shù)據(jù)存儲容器(為了演示方便,設(shè)置容量最多存儲 1 個元素) 
  6.     private int size = 0;               // 實際存儲大小 
  7.  
  8.     /** 
  9.      * 生產(chǎn)方法 
  10.      * @throws InterruptedException 
  11.      */ 
  12.     public synchronized void put() throws InterruptedException { 
  13.         // 循環(huán)生產(chǎn)數(shù)據(jù) 
  14.         do { 
  15.             while (size == items.length) { // 注意不能是 if 判斷 
  16.                 // 存儲的容量已經(jīng)滿了,阻塞等待消費者消費之后喚醒 
  17.                 System.out.println(Thread.currentThread().getName() + " 進入阻塞"); 
  18.                 this.wait(); 
  19.                 System.out.println(Thread.currentThread().getName() + " 被喚醒"); 
  20.             } 
  21.             System.out.println(Thread.currentThread().getName() + " 開始工作"); 
  22.             items[0] = 1; // 為了方便演示,設(shè)置固定值 
  23.             size++; 
  24.             System.out.println(Thread.currentThread().getName() + " 完成工作"); 
  25.             // 喚醒所有線程 
  26.             this.notifyAll(); 
  27.         } while (true); 
  28.     } 
  29.  
  30.     /** 
  31.      * 消費方法 
  32.      * @throws InterruptedException 
  33.      */ 
  34.     public synchronized void take() throws InterruptedException { 
  35.         // 循環(huán)消費數(shù)據(jù) 
  36.         do { 
  37.             while (size == 0) { 
  38.                 // 生產(chǎn)者沒有數(shù)據(jù),阻塞等待 
  39.                 System.out.println(Thread.currentThread().getName() + " 進入阻塞(消費者)"); 
  40.                 this.wait(); 
  41.                 System.out.println(Thread.currentThread().getName() + " 被喚醒(消費者)"); 
  42.             } 
  43.             System.out.println("消費者工作~"); 
  44.             size--; 
  45.             // 喚醒所有線程 
  46.             this.notifyAll(); 
  47.         } while (true); 
  48.     } 

依舊是兩個生產(chǎn)者加一個消費者,實現(xiàn)代碼如下:

  1. public static void main(String[] args) { 
  2.     Factory factory = new Factory(); 
  3.     // 生產(chǎn)者 
  4.     Thread producer = new Thread(() -> { 
  5.         try { 
  6.             factory.put(); 
  7.         } catch (InterruptedException e) { 
  8.             e.printStackTrace(); 
  9.         } 
  10.     }, "生產(chǎn)者"); 
  11.     producer.start(); 
  12.  
  13.     // 生產(chǎn)者 2 
  14.     Thread producer2 = new Thread(() -> { 
  15.         try { 
  16.             factory.put(); 
  17.         } catch (InterruptedException e) { 
  18.             e.printStackTrace(); 
  19.         } 
  20.     }, "生產(chǎn)者2"); 
  21.     producer2.start(); 
  22.  
  23.     // 消費者 
  24.     Thread consumer = new Thread(() -> { 
  25.         try { 
  26.             factory.take(); 
  27.         } catch (InterruptedException e) { 
  28.             e.printStackTrace(); 
  29.         } 
  30.     }, "消費者"); 
  31.     consumer.start(); 

執(zhí)行的結(jié)果如下圖所示:

通過以上結(jié)果可以看出:當(dāng)我們調(diào)用 notifyAll 時確實不會造成線程“假死”了,但會造成所有的生產(chǎn)者都被喚醒了,但因為待執(zhí)行的任務(wù)只有一個,因此被喚醒的所有生產(chǎn)者中,只有一個會執(zhí)行正確的工作,而另一個則是啥也不干,然后又進入等待狀態(tài),這種行為對于整個程序來說,無疑是多此一舉,只會增加線程調(diào)度的開銷,從而導(dǎo)致整個程序的性能下降。

反觀 Condition 的 await 和 signal 方法,即使有多個生產(chǎn)者,程序也只會喚醒一個有效的生產(chǎn)者進行工作,如下圖所示:


生產(chǎn)者和生產(chǎn)者 2 依次會被交替的喚醒進行工作,所以這樣執(zhí)行時并沒有任何多余的開銷,從而相比于 notifyAll 而言整個程序的性能會提升不少。

總結(jié)

本文我們通過代碼和流程圖的方式演示了 wait 方法和 notify/notifyAll 方法的使用缺陷,它的缺陷主要有兩個,一個是在極端環(huán)境下使用 notify 會造成程序“假死”的情況,另一個就是使用 notifyAll 會造成性能下降的問題,因此在進行線程通訊時,強烈建議使用 Condition 類來實現(xiàn)。

PS:有人可能會問為什么不用 Condition 的 signalAll 和 notifyAll 進行性能對比?而使用 signal 和 notifyAll 進行對比?我只想說,既然使用 signal 可以實現(xiàn)此功能,為什么還要使用 signalAll 呢?這就好比在有暖氣的 25 度的房間里,穿一件短袖就可以了,為什么還要穿一件棉襖呢?

責(zé)任編輯:姜華 來源: Java中文社群
相關(guān)推薦

2022-10-27 21:34:28

數(shù)據(jù)庫機器學(xué)習(xí)架構(gòu)

2020-12-11 09:24:19

Elasticsear存儲數(shù)據(jù)

2020-12-04 10:05:00

Pythonprint代碼

2020-12-02 11:18:50

print調(diào)試代碼Python

2020-06-15 08:12:51

try catch代碼處理器

2024-03-14 08:15:18

COUNT(*)數(shù)據(jù)庫LIMIT 1?

2020-11-09 08:22:29

程序員 IT科技

2024-06-12 13:54:37

編程語言字符串代碼

2020-12-07 06:05:34

apidocyapiknife4j

2021-06-09 06:41:11

OFFSETLIMIT分頁

2021-05-11 07:10:18

標(biāo)準(zhǔn)庫DjangoOS

2023-12-08 14:37:51

接口jar包開發(fā)

2020-09-22 09:05:45

MySQLUTF-8utf8mb4

2023-10-26 16:33:59

float 布局前段CSS

2021-05-25 09:30:44

kill -9Linux kill -9 pid

2021-01-29 11:05:50

PrintPython代碼

2020-12-03 09:05:38

SQL代碼方案

2025-02-10 08:05:03

2020-04-16 08:22:11

HTTPS加解密協(xié)議

2024-12-26 07:47:20

點贊
收藏

51CTO技術(shù)棧公眾號