public class ProducerConsumer {
/**
* 生产者消费者问题
*/
private static final int BUFFER_SIZE = 10;//缓冲池大小
private static int low;//消费下标
private static int high;//生产下标
private static int count;//信号量:当前产品数
static Product[] products;//产品线
static Monitor monitor = new Monitor();
public static void main(String[] args) {
init();
new Thread(new Consumer()).start();
new Thread(new Producer()).start();
}
//缓冲区初始化
public static void init(){
products = new Product[BUFFER_SIZE];
for(int i=0;i<BUFFER_SIZE;i++){
products[i] = new Product();
}
}
static class Monitor{
/*
* 管程
*/
public synchronized void insertProduct(){
//当缓冲区有空闲空间,则进行生产
if(count<BUFFER_SIZE-1){
count ++;
high ++;
high = high % BUFFER_SIZE;
products[high].setProductId(high);
notifyAll();//唤醒等待中的线程
System.out.println("正在生产,产品下标:"+products[high].getProductId());
}
else{
try {
System.out.println("生产者正在等待消费者消费");
wait();
} catch (InterruptedException e) {
System.out.println("Producer wait failure!!!");
e.printStackTrace();
}
}
}
public synchronized void removeProduct(){
//若缓冲池中没有产品,则进行等待
if(count <= 0){
try {
System.out.println("消费者正在等待产品");
wait();
} catch (InterruptedException e) {
System.out.println("Consumer wait failure!!!");
e.printStackTrace();
}
}
else{
count --;
low ++;
low = low % BUFFER_SIZE;
notifyAll();//唤醒等待中的线程
System.out.println("正在消费,产品下标:"+products[low].getProductId());
}
}
}
static class Consumer implements Runnable{
/*
* 消费者
*/
public void run() {
while(true){
monitor.removeProduct();
}
}
}
static class Producer implements Runnable{
/*
* 生产者
*/
public void run() {
while(true){
monitor.insertProduct();
}
}
}
static class Product {
/*
* 产品类
*/
private int productId;
//省略其他属性
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
}
}
生产者消费者问题--JAVA模拟
最新推荐文章于 2022-10-26 17:00:47 发布