zoukankan      html  css  js  c++  java
  • 生产者—消费者模式示例

    package producerAndCustomer;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Plate {
        private List<Object> apples = new ArrayList<Object>();
        public synchronized void putApple(Object apple){
            if(apples.size()>0){
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            apples.add(apple);
            notify();
            System.out.println("放了一个苹果");
        }
        public synchronized void getApple(){
            if(apples.size()==0){
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            Object apple = apples.get(0);
            apples.clear();
            notify();
            System.out.println("get了一个红苹果");
            
        }
        
    }
    package producerAndCustomer;
    
    public class Add implements Runnable {
        private Plate applePlate;
        private Object apple = new Object();
        public Add(Plate applePlate){
            this.applePlate = applePlate;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            for(int i = 0 ;i<5;i++){
                applePlate.putApple(apple);
            }
    
        }
    
    }
    package producerAndCustomer;
    
    public class Get implements Runnable {
        private Plate applePlate;
        public Get(Plate applePlate){
            this.applePlate = applePlate;
        }
        @Override
        public void run() {
            // TODO Auto-generated method stub
            for(int i=0;i<5;i++){
                applePlate.getApple();
            }
        }
    
    }
    package producerAndCustomer;
    
    public class SynchroTest {
    	public static void main(String args[]){
    		Plate myPlate = new Plate();
    		new Thread(new Get(myPlate)).start();
    		new Thread(new Add(myPlate)).start();
    	}
    }
    

      

  • 相关阅读:
    99%的人都理解错了HTTP中GET与POST的区别
    idea 使用
    一道java算法题
    记一次jedis并发使用问题JedisException: Could not return the resource to the pool
    我珍藏的神兵利器
    记一次诡异的debug
    spring cloud config
    spring mvc 集成quartz
    git使用下
    Mongo--03 mongo副本集、备份与恢复
  • 原文地址:https://www.cnblogs.com/Keven02/p/7410381.html
Copyright © 2011-2022 走看看