java 线程中的生产者和消费者模式

生产者和消费者的应用场景举例

比如用户注册时,可能会需要手机号验证,但是手机号验证是需要时间的,也是有数量上限的,如果同时有大量的用户使用手机号验证,就需要排队等待。

代码举例

生产者线程往篮子里放馒头,消费者线程取出馒头。假设篮子最多可放6个馒头,当篮子被放满时,生产者线程就需要等待。当消费者取出一个馒头时,就可以激活生产者线程,当篮子里的馒头被取完时,消费者线程就需要等待。

package com.test.producerConsumer;

public class Basket {
    
    
	
	int index=0;
	
	ManTou[] manTous=new ManTou[6];
	
	//往篮子中放馒头
	public synchronized void push(ManTou manTou)
	{
    
    
		//篮子满了 需要等待
		 if(index==6)
			try {
    
    
				this.wait();
			} catch (InterruptedException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 this.notify(); //唤醒的是pop中的wait方法 一旦放馒头了 则说明篮子中有馒头了 取馒头的方法不用等了
		 this.manTous[index]=manTou;
		 index++;	
	}	
	//从篮子中取馒头
	public synchronized ManTou pop()
	{
    
    
		if(index==0)
			try {
    
    
				this.wait();
			} catch (InterruptedException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		this.notify(); //唤醒的是push中的wait方法  一旦取馒头了 则说明篮子有空位了 放馒头的行为就不用等了
		index--;
		return this.manTous[index];
	}
	
	
	

}

package com.test.producerConsumer;

public class ManTou {
    
    

	int id;
	
	public ManTou(int id)
	{
    
    
		this.id=id;
	}
	
	
	public String toString()
	{
    
    
		return "ManTou[id="+this.id+"]";
	}
	
}

package com.test.producerConsumer;

public class Consumer extends Thread{
    
    
	
	Basket basket=null;
	
	public Consumer(Basket basket)
	{
    
    
		this.basket=basket;
	}
	//执行任务
	public void run()
	{
    
    
		for(int i=1;i<=20;i++)
		{
    
    
		   ManTou manTou=	this.basket.pop();
		   
		   System.out.println("消费了"+manTou);
		   
		   try {
    
    
			this.sleep(500);
		} catch (InterruptedException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
		
	}

}

package com.test.producerConsumer;

public class Producer extends Thread{
    
    
	
	  Basket basket=null;
	  
	  public Producer(Basket basket)
	  {
    
    
		  this.basket=basket;
	  }
	  
	  //执行任务
	  public void run()
	  {
    
    
		  for(int i=1;i<=20;i++)
		  {
    
    
			  ManTou manTou=new ManTou(i);
			  
			  basket.push(manTou);
			  
			  System.out.println("生产了"+manTou);
			  
			  try {
    
    
				this.sleep(200);
			} catch (InterruptedException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		  }
		  
	  }
	

}

package com.test.producerConsumer;

public class Test {
    
    

	/**
	 * @param args
	 */
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub

		Basket basket=new Basket();
		
		Producer producer=new Producer(basket);
		
		Consumer consumer=new Consumer(basket);
		
		producer.start();
		
		consumer.start();
		
		
	}

}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Rockandrollman/article/details/130471240