业务需求:
生产20个馒头,篮子里只能放6个馒头。
消费者发现篮子里有馒头可以食用时即可把馒头取出开始使用,直到篮子里馒头为空。
生产者发现篮子里的馒头不满足6个时,生产者开始生产馒头并放入篮子中。
具体实现:
第一步:创建盛放馒头的篮子类
第二步:创建生产者类
第三步:创建消费者类
第四步:创建馒头对象类
第五步:创建测试类
到此生产者消费者的小例子结束,希望能起到抛砖引玉的作用。
生产20个馒头,篮子里只能放6个馒头。
消费者发现篮子里有馒头可以食用时即可把馒头取出开始使用,直到篮子里馒头为空。
生产者发现篮子里的馒头不满足6个时,生产者开始生产馒头并放入篮子中。
具体实现:
第一步:创建盛放馒头的篮子类
- public class SyncBasket {
- public Bread[] breads = new Bread[6];
- private int index = 0;
- public synchronized void push(Bread bread ) {
- while(index==this.breads.length){
- try{
- this.wait();
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- this.notifyAll();
- breads[index]=bread;
- index++;
- }
- public synchronized Bread pop() {
- while(index==0){
- try{
- this.wait();
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- }
- this.notifyAll();
- index--;
- return breads[index];
- }
- }
第二步:创建生产者类
- public class Producer implements Runnable {
- private SyncBasket basket;
- public Producer(SyncBasket basket) {
- this.basket = basket;
- }
- public void run() {
- for(int i=1;i<21;i++){
- Bread bread = new Bread(i);
- basket.push(bread);
- System.out.println("producer produce: " + bread);
- try {
- Thread.sleep((int) (Math.random() * 1000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
第三步:创建消费者类
- public class Consumer implements Runnable {
- private SyncBasket basket;
- public Consumer(SyncBasket basket) {
- this.basket = basket;
- }
- public void run() {
- for(int i=0; i<20; i++) {
- Bread bread = basket.pop();
- System.out.println("Consumer eat: "+bread);
- try {
- Thread.sleep((int) (Math.random() * 1000));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
第四步:创建馒头对象类
- public class Bread {
- private int id;
- public Bread(int id){
- this.id=id;
- }
- @Override
- public String toString() {
- return String.valueOf(id);
- }
- }
第五步:创建测试类
- public class TestProConsumer {
- public static void main(String[] args) {
- SyncBasket basket=new SyncBasket();
- Producer producer=new Producer(basket);
- Consumer consumer=new Consumer(basket);
- new Thread(producer).start();
- new Thread(consumer).start();
- }
- }
到此生产者消费者的小例子结束,希望能起到抛砖引玉的作用。