學習筆記 1 高效能程式設計 1 1 5 執行緒通訊

2021-09-24 21:43:31 字數 2617 閱讀 6123

通訊方式

要想實現多個執行緒之間的協同,如:執行緒執行先後順序,獲取某個執行緒執行的結果等等。設計到執行緒之間相互通訊,分為下面四類:

檔案共享

網路共享

共享變數

jdk提供的執行緒協調api:細分為 suspend/resume,wait/notify,park/unpark

public class demo6 

public void suspendresumetest() throws exception

system.out.println("2、買到包子,回家");

});consumerthread.start();

thread.sleep(3000l);

baozidian = new object();

consumerthread.resume();

system.out.println("3、通知消費者");

}/** 死鎖的suspend/resume。 suspend並不會像wait一樣釋放鎖,故此容易寫出死鎖** */

public void suspendresumedeadlocktest() throws exception

system.out.println("2、買到包子,回家");

}});

consumerthread.start();

thread.sleep(3000l);

baozidian = new object();

synchronized (this)

system.out.println("3、通知消費者");

}/** 導致程式永久掛起的suspend/resume */

public void suspendresumedeadlocktest2() throws exception catch (interruptedexception e)

thread.currentthread().suspend();

}system.out.println("2、買到包子,回家");

});consumerthread.start();

thread.sleep(3000l);

baozidian = new object();

consumerthread.resume();

system.out.println("3、通知消費者");

}/** 正常的wait/notify */

public void waitnotifytest() throws exception catch (interruptedexception e) }}

system.out.println("2、買到包子,回家");

}).start();

thread.sleep(3000l);

baozidian = new object();

synchronized (this)

}/** 會導致程式永久等待的wait/notify */

public void waitnotifydeadlocktest() throws exception catch (interruptedexception e1)

synchronized (this) catch (interruptedexception e) }}

system.out.println("2、買到包子,回家");

}).start();

thread.sleep(3000l);

baozidian = new object();

synchronized (this)

}/** 正常的park/unpark */

public void parkunparktest() throws exception

system.out.println("2、買到包子,回家");

});consumerthread.start();

thread.sleep(3000l);

baozidian = new object();

locksupport.unpark(consumerthread);

system.out.println("3、通知消費者");

}/** 死鎖的park/unpark */

public void parkunparkdeadlocktest() throws exception

}system.out.println("2、買到包子,回家");

});consumerthread.start();

thread.sleep(3000l);

baozidian = new object();

synchronized (this)

system.out.println("3、通知消費者");

}}

警告:**中不能用if作為條件判斷是否進入等待狀態。

官方建議應該在迴圈中檢查等待條件,原因是處於等待狀態的執行緒可能會受到錯誤警報和偽喚醒,如果不在迴圈中檢查等待條件,程式就會在沒有滿足結束條件的情況下退出。

偽喚醒是指執行緒並非因為notify,notifyall,unpark等api呼叫而喚醒,是更底層原因導致的。

《GPU高效能程式設計CUDA實戰》學習筆記 1

gpu高效能程式設計cuda實戰 中 整理 gpu高效能程式設計cuda實戰 學習筆記 三 cuda程式設計 gpu架構,由sp,sm,thread,block,grid,warp說起 cuda並行程式設計 gpu程式設計指南 讀書筆記 1 執行緒網格 執行緒塊以及執行緒 sp streaming ...

高效能Mysql學習筆記 1 總覽

高效能mysql 這本經典之作,是個程式設計師就會買買買,但真正看完的確實不易。本篇部落格記錄的,也只是本人第一遍快速閱讀完之後的乙個簡易總結和記錄,尚未未深入學習,但已經感受到此書的 神力 似乎沒有這本書解決不了的問題 前提是要對本書的每乙個字都要深入研究 看似700多頁的一本書,實際學習起來,恐...

Linux高效能伺服器程式設計筆記1

要學習socket位址先要理解主機位元組序和網路位元組序。什麼是主機位元組序和網路位元組序?學習之前了解大小端位元組序 以整數 int i 1 為例 大端位元組序 記憶體的高位址存乙個數的低位位元組 0 7bit 記憶體的低位址存這個數的高位位元組 23 31bit 小端位元組序 記憶體的高位址存乙...