JAVA多线程经典范列:生产者与消费者
2023-09-27 14:23:13 时间
* 第一:生产者 生产的消费品 存放到仓库中,当仓库满时,生产者停止生产
* 第二:消费者 到仓库中 使用消费品,当仓库没有消费品时,停止消费
* 第三:生产者 在仓库满停止生产后 通知消费者去消费
* 第四:消费者 在仓库没有消费品时 通知生产者生产
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]; //仓库只能存放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();
}
}
}
}
相关文章
- java基础---->多线程之interrupt(九)
- java基础---->多线程之priority(四)
- java中Set,Map,Stack一些简单用法
- 如何理解 Java 多线程
- java多线程状态转换
- java多线程 synchronized关键字的一些用法
- java 多线程 Callable中的futrue模式
- Java基础知识1 java基础&jdk常用命令
- 2020十一届蓝桥杯Java的B组国赛 划水签到打卡
- Java 多线程(一)—— 概念的引入
- Java_java多线程下载-断点下载-超详细
- Java多线程之~~~线程安全容器的非堵塞容器
- Java多线程(六) wait/notify
- 阻止Java反编译蛋疼方法
- Java RMI详解
- java web开发(IDEA安装 + 第一个java工程)
- java多线程-Exchanger
- Java多线程和并发基础面试问答,看过后你不会后悔
- Java数组之杨辉三角
- Java多线程-BlockingQueue-ArrayBlockingQueue-LinkedBlockingQueue
- eclipse 运行简单JAVA程序事例
- 大数据必学Java基础(三十):IDEA的使用介绍
- LeetCode-191.位1的个数(java)
- Java SPI机制实战详解及源码分析
- Java多线程实现的四种方式