问题描述:生产者的主要作用是生成一定量的数据放到缓冲区中,然后重复此过程。与此同时,消费者也在缓冲区消耗这些数据。该问题的关键就是要保证生产者不会在缓冲区满时加入数据,消费者也不会在缓冲区中空时消耗数据。
Test.java
package com.oracle.test5;
public class Test {
public static void main(String[] args) {
BufferPool bp=new BufferPool(10);
Productor p=new Productor(bp);
Custmer c=new Custmer(bp);
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
}
}
BufferPool.java
package com.oracle.test5;
public class BufferPool {
private int capacity;//最大容量
private int count=0;//当前数量
public BufferPool(int capacity) {
super();
this.capacity = capacity;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public synchronized void add(){
while(count>=capacity){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count++;
System.out.println("生产一个后剩余:"+count);
notify();
}
public synchronized void sub(){
while(count==0){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
count--;
System.out.println("消费一个后剩余:"+count);
notify();
}
}
Custmer.java
package com.oracle.test5;
public class Custmer implements Runnable{
private BufferPool bufferpool;
public Custmer(BufferPool bufferpool) {
super();
this.bufferpool = bufferpool;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
bufferpool.sub();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Productor.java
package com.oracle.test5;
public class Productor implements Runnable{
private BufferPool bufferpool;
public Productor(BufferPool bufferpool) {
super();
this.bufferpool = bufferpool;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
bufferpool.add();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}