【转】生产者消费者问题应用:两个线程交替打印A、B各10次

[代码][Java]代码     跳至 [1] [全屏预览]

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 打印机类
public class Printer {
     
     private boolean hasBufferToPrint = false ;   // 打印缓冲区是否有内容可以打印
 
     // 打印A:相当于生产者,放一张纸
     public synchronized void printA() {
         while (hasBufferToPrint) {   // 缓冲区还有内容
             try {
                 wait();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         
         System.out.print( "A" );
         hasBufferToPrint = true ;
         
         notify();   // 唤醒打印B的线程
     }
     
     // 打印B:相当于消费者,消耗缓冲区中的纸,打印纸张
     public synchronized void printB() {
         while (!hasBufferToPrint) {
             try {
                 wait();
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         
         System.out.print( "B" );
         hasBufferToPrint = false ;
         
         notify();   // 唤醒打印A的线程
     }
 
     static class ThreadA extends Thread {
         private Printer printer;
 
         public ThreadA(Printer printer) {
             this .printer = printer;
         }
 
         public void run() {
             for ( int i = 0 ; i < 10 ; i++) {
                 printer.printA();
             }
         }
     }
 
     static class ThreadB extends Thread {
         private Printer printer;
         
         public ThreadB(Printer printer) {
             this .printer = printer;
         }
         
         public void run() {
             for ( int i = 0 ; i < 10 ; i++) {
                 printer.printB();
             }
         }
     }
 
     public static void main(String args[]) {
         Printer printer = new Printer();   // A、B线程共享同一个打印机
         Thread a = new ThreadA(printer);
         Thread b = new ThreadB(printer);
         
         a.start();
         b.start();
     }
}


转载于:https://my.oschina.net/u/2393600/blog/468205

你可能感兴趣的:(【转】生产者消费者问题应用:两个线程交替打印A、B各10次)