多线程_并发协作_管程法

 1 /**
 2  * 多线程_并发协作_管程法
 3  *
 4  * @author: mhSui 2020/04/21
 5  */
 6 public class Test01 {
 7     public static void main(String[] args) {
 8         SynContainer container = new SynContainer();
 9         new Productor(container).start();
10         new Consumer(container).start();
11     }
12 }
13 
14 //生产者
15 class Productor extends Thread{
16     SynContainer container;
17     public Productor(SynContainer container){
18         this.container = container;
19     }
20 
21     @Override
22     public synchronized void run() {
23         //生产玩具
24         for (int i = 0;i < 100;i++){
25             System.out.println("生产-->"+ i +"个玩具");
26             container.push(new ProductNum(i));
27         }
28     }
29 }
30 
31 //消费者
32 class Consumer extends Thread{
33     SynContainer container;
34     public Consumer(SynContainer container){
35         this.container = container;
36     }
37 
38     @Override
39     public void run() {
40         //消费
41         for (int i = 0;i < 100;i++){
42             System.out.println("消费-->"+ container.pop().id +"个玩具");
43         }
44     }
45 }
46 
47 //存放容器——仓库
48 class SynContainer{
49     //存储容器
50     ProductNum[] productNums = new ProductNum[10];
51     //计数器
52     int count = 0;
53     //存储 生产
54     public synchronized void push(ProductNum productNum){
55         //何时能生产 容器存在空间
56         //不能生产
57         if (count == productNums.length){
58             try {
59                 this.wait();//线程阻塞 消费者者通知生产者解除
60             } catch (InterruptedException e) {
61                 e.printStackTrace();
62             }
63         }
64         productNums[count] = productNum;
65         count++;
66         //存在数据了,通知消费者消费数据
67         this.notifyAll();
68     }
69 
70     //消费 获取
71     public synchronized ProductNum pop(){
72         //何时消费 容器中是否存在数据
73         //没有数据 只有等待
74         if (count == 0){
75             try {
76                 this.wait();//线程阻塞 生产通知消费解除
77             } catch (InterruptedException e) {
78                 e.printStackTrace();
79             }
80         }
81         //存在数据可以消费
82         count--;
83         ProductNum productNum = productNums[count];
84         this.notifyAll();//存在空间 唤醒生产者生产
85         return productNum;
86     }
87 }
88 
89 //生产的产品
90 class ProductNum{
91   int id;//给生产的产品加个编号
92   public ProductNum(int id){
93       this.id = id;
94   }
95 }
原文地址:https://www.cnblogs.com/mhSui/p/12745826.html