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();
    	}
    }
    

      

  • 相关阅读:
    第五周笔记
    第四周笔记——复制文件(可读时间)
    第三周笔记
    java第6次作业
    java第五次作业
    java第四次作业
    java第三次作业
    第一周Java笔记
    计划进度表
    第六次作业
  • 原文地址:https://www.cnblogs.com/Keven02/p/7410381.html
Copyright © 2011-2022 走看看