交叉輸出字串A或B,各輸出若干次
阿新 • • 發佈:2021-06-22
1 public class DBTools { 2 3 private volatile boolean flag = false; 4 5 public synchronized void backupA(){ 6 try { 7 while(flag){ //當為true阻塞 8 this.wait(); 9 } 10 11 for (int i = 0; i < 5; i ++){ 12 System.out.println("AAAAAAAA");13 } 14 15 flag = true; 16 this.notifyAll(); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 } 21 22 public synchronized void backupB(){ 23 try { 24 while(!flag){ //當為false阻塞 25 this.wait(); 26 } 27 28 for (int i = 0; i < 5; i ++){ 29 System.out.println("BBBBBBBB"); 30 } 31 32 flag = false; 33 this.notifyAll(); 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 }37 } 38 }
1 public class ThreadA extends Thread{ 2 3 private DBTools dbTools; 4 5 public ThreadA(DBTools dbTools){ 6 this.dbTools = dbTools; 7 } 8 9 @Override 10 public void run() { 11 dbTools.backupA(); 12 } 13 }
1 public class ThreadB extends Thread{ 2 3 private DBTools dbTools; 4 5 public ThreadB(DBTools dbTools){ 6 this.dbTools = dbTools; 7 } 8 9 @Override 10 public void run() { 11 dbTools.backupB(); 12 } 13 }
1 public class Run { 2 3 public static void main(String[] args) { 4 DBTools tools = new DBTools(); 5 for (int i = 0; i < 10; i ++){ 6 ThreadA a = new ThreadA(tools); 7 a.start(); 8 9 ThreadB b = new ThreadB(tools); 10 b.start(); 11 } 12 } 13 }
備註:來源於書籍(高洪巖)Java多執行緒程式設計核心技術-177頁