java多线程之生产者消费者模型

本文详细解析了一个Java线程通信的实例,通过生产者和消费者模式,利用synchronized关键字和wait/notify方法实现线程间的同步。展示了如何在多线程环境中控制资源的访问,确保数据的一致性和线程安全。
 1 public class ThreadCommunication{
 2     public static void main(String[] args) {
 3         
 4         Queue q = new Queue();//创建,并初始化一个队列
 5         
 6         Thread p1 = new Thread(new Product(q));
 7         Thread c1 = new Thread(new Consumer(q));
 8         
 9         c1.start();
10         p1.start();
11     }
12 }
13 
14 class Product implements Runnable {
15     
16     Queue q ; //声明队列
17     public Product(Queue q) {
18         this.q = q;
19     }
20 
21     public void run() {
22         for(int i=1; i<5;i++){
23             q.put(i);
24         }
25     }
26 }
27 class Consumer implements Runnable {
28     
29     Queue q ; //声明队列
30     public Consumer(Queue q) {
31         this.q = q;
32     }
33 
34     public void run() {
35         while(true){
36             q.get();//循环消费,每次消费了一个元素
37         }
38     }
39 }
40 
41 class Queue {
42     int value = 0;
43     boolean isEmpty = true;
44     //生产方法
45     public synchronized void put(int v){
46         if(!isEmpty){
47             System.out.println("共享数据没有被消费,生产者等待...");
48             try {
49                 wait();//进入等待状态
50             } catch (InterruptedException e) {
51                 e.printStackTrace();
52             }
53         }
54         value += v;
55         isEmpty = false; //不为空了
56         System.out.println("生产者产品数量:"+value);
57         notify();//通知消费者
58     }
59     //消费方法
60     public synchronized int get(){
61         
62         if(isEmpty){
63             try {
64                 System.out.println("共享数据为空,消费者等待...");
65                 wait();
66             } catch (InterruptedException e) {
67                 e.printStackTrace();
68             }
69         }
70         value--;
71         if(value < 1){
72             isEmpty = true;
73         }
74         System.out.println("消费者消费了一个,剩余:"+value);
75         notify();
76         return value;//返回剩余的产品总数
77     }
78 }

运行结果:

 

转载于:https://www.cnblogs.com/xianlei/p/7884655.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值