在编辑多线程的生产者-消费者模型的过程中,发现执行结果不符合理想结果,超出了限制。
1、问题:超过仓库容量,生产者继续生产。
2、代码:
public class producerAndConsumer {
public static void main(String[] args) {
LinkedList<Integer> list= new LinkedList<Integer>();
MessageQueue queue = new MessageQueue(list,3);//仓库队列,容量设置为3
//创建并启动3个生产的线程
for (int i = 1; i <= 3; i++) {
new Thread(()->{
int obj = 0;
int j=0; //控制次数
while(j<10){
j++;
queue.producer(obj);
obj++;
}
},"producer"+i).start();
}
//创建并启动消费的线程
new Thread(()->{
int j=0; //控制次数
while(j<10){
j++;
queue.consumer();
}
},"consumer").start();
}
/**
* 生产消费队列
*/
static class MessageQueue{
private LinkedList<Integer> list;
private int capacity; //容量
//生产
public void producer(Integer obj){
synchronized (this.list){
if(list.size()==capacity){
try {
System.out.println("仓库已满-------------->停止生产!");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add(obj);
System.out.println(Thread.currentThread().getName()+"生产:"+obj+",size:"+list.size()+"--仓库:"+list);
list.notifyAll();
}
}
//消费方法
public Integer consumer(){
synchronized (this.list){
if(list.isEmpty()){
try {
System.out.println("仓库已空-------------->停止消费!");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer obj = list.remove();
System.out.println(Thread.currentThread().getName()+"消费:"+obj+",size:"+list.size()+"--仓库:"+list);
list.notifyAll();
return obj;
}
}
//构造方法
public MessageQueue(LinkedList<Integer> list,int capacity){
this.list = list;
this.capacity = capacity;
}
}
}
3、执行结果: