1. 程式人生 > 其它 >利用執行緒通訊,寫2個執行緒,一個執行緒列印1~52,另一個執行緒列印A~Z,列印順序應該使12A34B56C···5152Z

利用執行緒通訊,寫2個執行緒,一個執行緒列印1~52,另一個執行緒列印A~Z,列印順序應該使12A34B56C···5152Z

利用執行緒通訊,寫2個執行緒,一個執行緒列印1~52,另一個執行緒列印A~Z,列印順序應該使12A34B56C···5152Z

Object類提供了執行緒間通訊的方法:wait()、notify()、notifyaAl(),它們是多執行緒通訊的基礎,而這種實現方式的思想自然是執行緒間通訊。

 1 public class ThreadTest06 {
 2     private boolean flag = true;
 3 
 4     /**
 5      * 列印兩個連續的整數
 6      *
 7      * @throws InterruptedException
 8      */
9 public synchronized void printNum() throws InterruptedException { 10 for (int i = 1; i < 53; ) { 11 if (!flag) { 12 wait(); 13 } else { 14 //兩個i++放到這程式只需迴圈一次就可以了 15 //不放在for迴圈體裡是防止執行緒喚醒後的多次疊加 16 System.out.print((i++) + "," + (i++) + ",");
17 flag = false; 18 notifyAll(); 19 } 20 } 21 } 22 23 /** 24 * 在兩個整數之間列印一個字母 25 * 26 * @throws InterruptedException 27 */ 28 public synchronized void printLetter() throws InterruptedException { 29 for (int i = 1; i < 27; ) {
30 if (flag) { 31 wait(); 32 } else { 33 System.out.print(i != 26 ? ((char) (i + 64) + ",") : ((char) (i + 64) + "\n")); 34 i++; 35 flag = true; 36 notifyAll(); 37 } 38 } 39 } 40 41 public static void main(String[] args) { 42 ThreadTest06 tt = new ThreadTest06(); 43 44 Runnable r1 = () -> { 45 try { 46 tt.printNum(); 47 } catch (InterruptedException e) { 48 e.printStackTrace(); 49 } 50 }; 51 Runnable r2 = () -> { 52 try { 53 tt.printLetter(); 54 } catch (InterruptedException e) { 55 e.printStackTrace(); 56 } 57 }; 58 59 new Thread(r1, "number").start(); 60 new Thread(r2, "letter").start(); 61 } 62 }