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();
}
}
展开