多執行緒筆試題記錄
阿新 • • 發佈:2021-07-26
執行緒題1
設定三個執行緒並行
t1列印a
t2列印b
t3列印c輸出abc abc abc abc
/** * * 設計三個執行緒併發執行 * t1 列印 a * t2 列印 b * t3 列印 c * * 輸出 abc abc abc abc * */ public class LockTest9 { public static void main(String[] args) { WaitNofity waitNofity = new WaitNofity(); //執行緒t1 new Thread(() ->{ try { waitNofity.print("a",1,2); } catch (InterruptedException e) { e.printStackTrace(); } },"t1").start(); //執行緒t2 new Thread(() ->{ try { waitNofity.print("b",2,3); } catch (InterruptedException e) { e.printStackTrace(); } },"t2").start(); //執行緒t3 new Thread(() ->{ try { waitNofity.print("c",3,1); } catch (InterruptedException e) { e.printStackTrace(); } },"t3").start(); } static class WaitNofity{ //執行標誌 int flag = 1; /** * @Param content 輸出內容 * @Param waitFlag 本次執行標誌 * @Param nextFlag 下次執行標誌 **/ public void print(String content,int waitFlag,int nextFlag) throws InterruptedException { for (int i = 0; i < 4; i++){ synchronized (this){ while (flag != waitFlag){ this.wait();//阻塞 } System.out.print(content); if(waitFlag == 3){ System.out.print(" "); } flag = nextFlag; this.notifyAll();//喚醒全部 } } } } }
執行結果: