设计思路:生产者push ,消费者 拿,篮子装,syncstack先进后出,while 判断 index=0 wait,      当 Producer生产了 并push到篮子里  notify(唤醒) 消费者。

wait:发生了阻塞事件-篮子已经满了,并且不知道阻塞多长时间,要用wait

public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
}
} class WoTou {//馒头和馒头的属性
int id;
WoTou(int id) {
this.id = id;
}
public String toString() {
return "WoTou : " + id;
}
} class SyncStack {//创建一个装馒头的“篮子”
int index = 0;
WoTou[] arrWT = new WoTou[6]; public synchronized void push(WoTou wt) {//放馒头方法
while(index == arrWT.length) {//一定要用while循环语句而不要用if,如果是if再wait阻塞被打断 报interruptedException printStackTrace后会直接执行notifyall 而不会反过来头判断篮子里馒头满了没有
try {
this.wait();//wait阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
arrWT[index] = wt;
index ++;
} public synchronized WoTou pop() {
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return arrWT[index];
}
} class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this.ss = ss;
} public void run() {
for(int i=0; i<20; i++) {
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("生产了:" + wt);
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this.ss = ss;
} public void run() {
for(int i=0; i<20; i++) {
WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

最新文章

  1. css 设置圆角
  2. Codeforces Round #389 (Div. 2, Rated, Based on Technocup 2017 - Elimination Round 3) C
  3. 位运算(&amp;)实现分享弹窗上的图标动态显示/隐藏
  4. 【bzoj1036】 ZJOI2008—树的统计Count
  5. 用JS写的无缝滚动特效
  6. memcached在linux安装
  7. GitHub开源:升讯威ADO.NET增强组件 sheng.ADO.NET.Plus V1.3
  8. MySQL unique 注意
  9. EJB开发第一个无状态会话bean、开发EJB客户端
  10. linux yum提示Loaded plugins: fastestmirror, security错误的解决方法
  11. P1462 通往奥格瑞玛的道路 最短路
  12. 阿里云 docker连接总报超时 registry.cn-hangzhou.aliyuncs.com (Client.Timeout exceeded while awaiting headers
  13. (reverse) Text Reverse hdu1062
  14. 如何使用less(变量,混合,匹配,运算,嵌套...)
  15. OBV15 案例2
  16. Ubuntu上安装MySQL
  17. Twisted 安装
  18. Hadoop 和 Spark 的关系
  19. symfony学习笔记1—简介
  20. linux convert命令安装及使用

热门文章

  1. samba服务器共享开发【windows下开发linux网站】
  2. jenkins slave Windows 2008 R2
  3. windows phone之依赖属性(DependencyProperty)
  4. Windows + python + pywinauto 搭建自动化测试环境
  5. 洛谷P4014 分配问题(费用流)
  6. 从图片中提取html格式的布局
  7. ThinkCMF Foreach标签
  8. Thinkphp5.1 URL重写 .htaccess文件
  9. sublime text3 添加新片段
  10. 在 Domoticz 中添加插座开关