JavaSE:线程 - 生产者与消费者模型

1.  图解

 

 

 

 

2.  代码示例

<1>  仓库类

 1 public class StoreHouse {
 2     private int cnt = 0; // 用于记录产品的数量
 3 
 4     public synchronized void produceProduct() {
 5         notify();
 6         if (cnt < 10) {
 7             System.out.println("线程" + Thread.currentThread().getName() + "正在生产第" + (cnt+1) + "个产品...");
 8             cnt++;
 9         } else {
10             try {
11                 wait();
12             } catch (InterruptedException e) {
13                 e.printStackTrace();
14             }
15         }
16     }
17 
18     public synchronized void consumerProduct() {
19         notify();
20         if (cnt > 0) {
21             System.out.println("线程" + Thread.currentThread().getName() + "消费第" + cnt + "个产品");
22             cnt--;
23         } else {
24             try {
25                 wait();
26             } catch (InterruptedException e) {
27                 e.printStackTrace();
28             }
29         }
30     }
31 }

<2>  生产者线程

 3 /**
 4  * 编程实现生产者线程,不断地生产产品
 5  */
 6 public class ProduceThread extends Thread {
 7     // 声明一个仓库类型的引用作为成员变量,是为了能调用调用仓库类中的生产方法   合成复用原则
 8     private StoreHouse storeHouse;
 9     // 为了确保两个线程共用同一个仓库
10     public ProduceThread(StoreHouse storeHouse) {
11         this.storeHouse = storeHouse;
12     }
13 
14     @Override
15     public void run() {
16         while (true) {
17             storeHouse.produceProduct();
18             try {
19                 Thread.sleep(1000);
20             } catch (InterruptedException e) {
21                 e.printStackTrace();
22             }
23         }
24     }
25 }

<3>  消费者线程

 1 public class ConsumerThread extends Thread {
 2     // 声明一个仓库类型的引用作为成员变量,是为了能调用调用仓库类中的生产方法   合成复用原则
 3     private StoreHouse storeHouse;
 4     // 为了确保两个线程共用同一个仓库
 5     public ConsumerThread(StoreHouse storeHouse) {
 6         this.storeHouse = storeHouse;
 7     }
 8 
 9     @Override
10     public void run() {
11         while (true) {
12             storeHouse.consumerProduct();
13             try {
14                 Thread.sleep(100);
15             } catch (InterruptedException e) {
16                 e.printStackTrace();
17             }
18         }
19     }
20 }

<4>  StoreHouseTest.java

public class StoreHouseTest {

    public static void main(String[] args) {

        // 创建仓库类的对象
        StoreHouse storeHouse = new StoreHouse();
        // 创建线程类对象并启动
        ProduceThread t1 = new ProduceThread(storeHouse);
        ConsumerThread t2 = new ConsumerThread(storeHouse);
        t1.start();
        t2.start();
    }
}

 

posted @ 2021-06-21 14:07  Jasper2003  阅读(39)  评论(0)    收藏  举报