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