寫兩個執行緒,一個執行緒列印 1~52,另一個執行緒列印A~Z, 列印順序是12A34B...5152Z
阿新 • • 發佈:2018-11-20
- 這個題目就是要用wait()和notify()方法來控制兩個執行緒的執行
- 看如下程式碼:
- 當標誌位flag為1 時,列印數字;否則列印字母
- count即為列印的數字
class Print { private int flag = 1; private int count = 1; public synchronized void printNum(){ while (flag != 1) { // 此時應該列印字母 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(2*count-1); System.out.print(2*count); flag = 2; notify(); } public synchronized void printChar(){ while (flag != 2) { // 此時應該列印數字 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print((char)(count-1+'A')); // 繼續前行 count++; flag = 1; notify(); } } public class Test{ public static void main(String[] args) { Print print = new Print(); new Thread(()->{ for (int i = 0;i < 26;i++) { print.printNum(); } }).start(); new Thread(() -> { for (int i = 0;i < 26;i++) { print.printChar(); } }).start(); } }