pv操作实现(代码简洁有效)

这是一个使用PV操作(即synchronized关键字和wait/notify方法)实现的生产者消费者模型。代码中定义了Product类作为共享资源,Producer类作为生产者线程,Consumer类作为消费者线程。生产者线程生产商品并唤醒消费者,消费者线程消费商品并可能调用wait()进入等待状态。当商品数量达到预设的最大值时,生产者停止生产;当商品数量为0时,消费者进入等待状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class Product{
static int count;//计数
static int NUM = 10;//缓冲区资源数
public static void main(String[] args){
Product p = new Product();
System.out.println("缓冲池总共能放"+NUM+"个商品");
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
Producer pd = new Producer(p,1);
pd.start();
Consumer cs = new Consumer(p,1);
cs.start();
Consumer cs1 = new Consumer(p,2);
cs1.start();
Consumer cs2 = new Consumer(p,3);
cs2.start();
Producer pd1 = new Producer(p,2);
pd1.start();
}
}


class Producer extends Thread{
Product p;int s;
Producer(Product p,int s ){
this.p = p;
this.s=s;
}

public void run(){
while(true){
if(produce())
continue;
else
break;
}
}

    boolean produce(){
synchronized (p) {//锁,对象监视器
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
Product.count++;
//Product.NUM++;
if(Product.count >= 1){
p.notify();
  System.out.println("第"+s+"个"+"生产者生产"+Product.count+"个商品");
}

if(Product.count >= Product.NUM){
return false;
}else{
return true;
}
}
   
}

}


class Consumer extends Thread{
Product p;int s;
Consumer(Product p,int s ){
this.p = p;
this.s =s;
}

public void run(){
while(true){
consume();
}
}
void consume(){
synchronized (p) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
if(Product.count >= 1){
    Product.count--;
   // Product.NUM--;
    System.out.println("第"+s+"个"+"消费者消费"+Product.count+"个商品");
}else{
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值