利用线程通信,写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 }

 

posted @ 2021-12-09 20:58  迷人的二哈  阅读(185)  评论(0编辑  收藏  举报