生产者消费者第二种情形


package com.maple.msb.one; 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) {
try {
this.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. mysql外键添加error1215
  2. [MySQL Reference Manual]14 InnoDB存储引擎
  3. Could not load type from string value 'DALMSSQL.DBSessionFactory,DALMSSQL'.
  4. c++实现螺旋矩阵分析总结
  5. Spring配置中的classpath和classpath*的区别
  6. JDK 环境变量设置
  7. KING小组
  8. KextWizard 的使用方法;以及Kext安装的几种工具下载
  9. 我所改造的JSocket适用于任何DELPHI版本
  10. 跨过slf4j和logback,直接晋级log4j 2
  11. sql Server 发送邮件 错误类型及原因
  12. ZOJ3527
  13. JS时间戳比较大小:对于一组时间戳(开始时间~结束时间)和另一组时间戳进行比较,用于判断被比较时间戳组是否在要求范围内
  14. LocalDate的使用
  15. Python 的名称空间和作用域
  16. 深入浅出PF 学习笔记---TypeConverter
  17. 复制到剪切板js代码(转)
  18. 使用JSP表达式和JSP脚本打印九九乘法表
  19. 解决Image在canvas以及audio、video在AudioContext下跨域问题
  20. Vue开发 localhost 替换成 本机ip无法访问

热门文章

  1. Excel的vlookup函数的用法
  2. 十一、spark SQL的scala示例
  3. iptables-linux(ls)-inode-block
  4. jquery appendTo用法
  5. 深入辨析jvm内存区域
  6. ArrayList封装
  7. DB2 Metadata
  8. CentOS6下docker的安装和使用
  9. BZOJ1968 [Ahoi2005] 约数研究
  10. [SD2015]序列统计——solution