標籤:資料 bool ide catch 資源 false dmi tor cep
面試題:
子線程迴圈10次,接著主線程迴圈100次,接著又回到子線程迴圈10次,接著又 主線程迴圈100次,如此迴圈50次,請寫出程式
/** * 子線程迴圈10次,接著主線程迴圈100次,接著又回到子線程迴圈10次,接著又 主線程迴圈100次,如此迴圈50次,請寫出程式 * * @author Administrator * */public class TraditionalThreadCommunication { public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 50; i++) { business.sub(i); } } }).start(); for (int i = 1; i <= 50; i++) { business.main(i); } }}class Business { private boolean isShoudeSub = true; /** * 同步加在需要訪問的資源的代碼上,不要放線上程上 * @param i */ public synchronized void sub(int i) { while (!isShoudeSub) { //這裡也可以用 if ,用while比較好一些 As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop try { // 防止線程有可能被假喚醒 (while放在這裡提現了水準) this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 100; j++) { System.out .println("sub thread sequence of " + j + ", loop of " + i); } isShoudeSub = false; this.notify(); } public synchronized void main(int i) { while (isShoudeSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("main thread sequence of " + j + ", loop of " + i); } isShoudeSub = true; this.notify(); } /** * * synchronized (obj) { 這裡的obj與obj.wait必須相同,否則會拋異常 while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition } */}
要用到共同資料(包括同步鎖)或共同演算法的若干個方法應該歸在同一個類身上,這種設計正好提現了高類聚和程式的健壯性。
Java多線程與並發庫進階應用程式-傳統線程同步通訊技術