生产者消费者pv操作JAVA_用java实现生产者消费者问题pv操作,不知道错哪里了。...

classS{intvalue;publicS(intn){value=n;}}//*****************************************************************classVar{intin=0,out=0,buffer[],count=0;Smutex=newS(1);Sempty=n...

class S{

int value;

public S(int n) {

value=n;

}

}

//*****************************************************************

class Var{

int in=0,out=0,buffer[],count=0;

S mutex= new S(1);

S empty = new S(20);

S full = new S(0);

}

//*****************************************************************

class PV extends Var{

synchronized void P(S n){//进行P操作

n.value--;

if(n.value<0) {

try {

this.wait();

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

synchronized void V(S n) {

n.value++;

if(n.value<=0)

this.notify();

}

}

//*****************************************************************

class Producer extends PV implements Runnable{

@Override

public void run() {

// TODO Auto-generated method stub

while(true) {

P(empty);

P(mutex);

count++;

System.out.println("生产一个"+count);

V(full);V(mutex);

}

}

}

//*****************************************************************

class Consumer extends PV implements Runnable{

@Override

public void run() {

// TODO Auto-generated method stub

while(true) {

P(full);

P(mutex);

System.out.println("消费了一个"+count);

V(mutex);

V(empty);

}

}

}

//*****************************************************************

public class Main {

public static void main(String[] args) {

Producer p = new Producer();

Consumer c = new Consumer();

Thread t1 = new Thread(p);

Thread t2 = new Thread(c);

t1.start();

t2.start();

}

}

展开

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值