Java多线程关于生产者和消费者
来源:互联网 发布:主播助手软件 编辑:程序博客网 时间:2024/06/01 13:17
生产者--消费者,二者共享数据(Student对象),这里,生产者是SetStudent, 消费者是GetStudent。生产者负责放物品到Student中,消费者使用wait( )等待生产者的通知。当得到通知后,消费者取出物品,并且用notify( )通知生产者,可以再放下一批物品。
(1)生产者仅仅在仓储未满时候生产,仓满则停止生产。
(2)消费者仅仅在仓储有产品时候才能消费,仓空则等待。
(3)当消费者发现仓储没产品可消费时候会通知生产者生产。
(4)生产者在生产出可消费产品时候,应该通知等待的消费者去消费
//学生实体类作为共享资源class Student { private String name;// 姓名 private int age;// 年龄 boolean flag;// 标记变量,判断当前学生对象是否已创建赋值好 //生产者的功能 ,为studnet对象赋值 public synchronized void set(String name, int age) { if (this.flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.name = name; this.age = age; this.flag = true; this.notify();//唤醒正在等待此对象的单个线程监控。如果有任何线程在这个对象上等待,其中一个线程被唤醒。选择是任意的 } //消费者的功能,打印sutdent对象的内容 public synchronized void get() { if (!this.flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(name + ":::" + age); this.flag = false; this.notify(); }}// 模拟生产者线程类class SetStudent implements Runnable { // 共享资源s private Student s; private int x = 0; public SetStudent(Student s) { this.s = s; } public void run() { while (true) { if (x % 2 == 0) { s.set("郭靖", 27); } else { s.set("黄蓉", 18); } x++; } }}// 模拟消费者线程类class GetStudent implements Runnable { // 共享资源s private Student s; public GetStudent(Student s) { this.s = s; } public void run() { while (true) { s.get(); } }}// 测试类public class Demo3{ public static void main(String[] args) { Student s = new Student(); SetStudent ss = new SetStudent(s); GetStudent gs = new GetStudent(s); Thread t1 = new Thread(ss, "生产者"); Thread t2 = new Thread(gs, "消费者"); t1.start(); t2.start(); }}
0 0
- Java多线程关于生产者和消费者
- Java 多线程 生产者和消费者
- Java多线程-生产者和消费者
- 关于Java多线程实现生产者和消费者的问题
- 关于Java多线程------(4,经典案例---生产者和消费者)
- 关于Java多线程生产者消费者实例
- java多线程 消费者-生产者
- java多线程 消费者-生产者
- java 多线程 生产者消费者
- JAVA [ 多线程 -- 生产者消费者 ]
- Java 多线程-生产者、消费者
- java多线程--生产者消费者
- java多线程-生产者消费者
- Java多线程生产者消费者
- java多线程-生产者消费者
- Java 多线程生产者和消费者代码示例
- java多线程中生产者和消费者范例
- -java多线程——生产者和消费者
- C++第五次实验
- tiny6410 通过按键玩中断
- MindManager中如何将思维导图设置为默认模板?
- 【SHOI&SXOI2017】bzoj4868 期末考试
- hive 创建表
- Java多线程关于生产者和消费者
- vim编辑器的简单使用
- HDU
- 项目中ajax请求第二次的乱码问题
- DOM2
- 中国大学生计算机设计大赛报名及作品提交攻略
- Commit failed with error ***remains in conflict 解决android studio svn文件冲突的问题
- 求最大面积
- 是时候客观评价Retrofit了,Retrofit这几点你必须明白!