写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z

题目:

写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z。要求用线程间的通信。


 1 /**
 2  * 写两个线程,第一个线程打印1-52,第二个线程打印A-Z,打印结果为12A34B...5152Z
 3  */
 4 public class ThreadPrinter {
 5     // true打印数字,false打印字母
 6     private boolean flag = true;
 7 
 8     // 打印字母
 9     public synchronized void printNumber(String s) {
10         try {
11             if (!flag) {
12                 super.wait();
13             }
14             System.out.print(s);
15             flag = false;
16             super.notifyAll();
17         } catch (InterruptedException ex) {
18         }
19     }
20 
21     // 打印数字
22     public synchronized void printLetter(String s) {
23         try {
24             if (flag) {
25                 super.wait();
26             }
27             System.out.print(s);
28             flag = true;
29             super.notifyAll();
30         } catch (InterruptedException ex) {
31         }
32     }
33 
34     /**
35      *线程2:打印A-Z
36      */
37     public static class LetterPrintThread extends Thread {
38         private ThreadPrinter printer;
39 
40         private LetterPrintThread(String name, ThreadPrinter printer) {
41             super(name);
42             this.printer = printer;
43         }
44 
45         @Override
46         public void run() {
47             for (int i = 1; i <= 26; i++) {
48                 int temp = i + 64;
49                 char c = (char) temp;
50                 printer.printLetter(c + " ");
51             }
52         }
53 
54     }
55 
56     /**线程1:打印1-52*/
57     public static class NumberPrintThread extends Thread {
58         private ThreadPrinter printer;
59 
60         private NumberPrintThread(String name, ThreadPrinter printer) {
61             super(name);
62             this.printer = printer;
63         }
64         @Override
65         public void run() {
66             for (int i = 1; i <= 26; i++) {
67                 String s = (2 * i - 1) + " " + 2 * i + " ";
68                 printer.printNumber(s);
69             }
70 
71         }
72     }
73 
74     public static void main(String[] args) {
75         ThreadPrinter printer = new ThreadPrinter();
76         new NumberPrintThread("打印数字线程", printer).start();
77         new LetterPrintThread("打印字母线程", printer).start();
78     }
79 }
 
posted @ 2019-12-18 17:24  初仰  阅读(2294)  评论(0编辑  收藏  举报