代码描述:
定义苹果的缓冲区:appleContainer类
apples数组:表示存苹果的数组
count:表示数组中的苹果数量
public synchronized void push(apple a):向缓冲区中加入苹果:当缓冲区满了,线程阻塞,否则进行生产,并唤醒其他的线程
public synchronized apple pop() :从缓冲区中取苹果,当缓冲区为空,线程阻塞,否则进行消费,并唤醒其他线程
package ThreadTest;
public class PC {
public static void main(String[] args) {
// TODO Auto-generated method stub
appleContainer ac = new appleContainer();
producer p = new producer(ac);
consumer c = new consumer(ac);
p.start();c.start();
}
}
class producer extends Thread{
appleContainer applecontainer;
public producer(appleContainer applecontainer) {
super();
this.applecontainer = applecontainer;
}
@Override
public void run() {
for(int i=0;i<100;i++) {
System.out.println("生产第"+i+"苹果");
applecontainer.push(new apple());
}
}
}
class consumer extends Thread{
appleContainer applecontainer;
public consumer(appleContainer applecontainer) {
super();
this.applecontainer = applecontainer;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<100;i++) {
System.out.println("消费第"+i+"苹果");
applecontainer.pop();
}
}
}
//缓冲区
class appleContainer{
apple []apples = new apple[100];
int count=0;
//存苹果
public synchronized void push(apple a){
if(count==apples.length) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notifyAll();
apples[count++] = a;
}
//取苹果
public synchronized apple pop() {
if(count==0) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notifyAll();
return apples[--count];
}
}
class apple{
}