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

      

  • 相关阅读:
    [转]MySQL日志——Undo | Redo
    linux查看系统的硬件信息
    Linux HDD information (SATA/SCSI/SAS/SSD)
    sysbench 0.5使用手册
    MYSQL数据丢失讨论
    innodb_flush_method理解
    快速从mysqldump文件中恢复一个表
    Python 交互模式中 Delete/Backspace 键乱码问题
    Django--源码安装
    greenplum-时间处理
  • 原文地址:https://www.cnblogs.com/Keven02/p/7410381.html
Copyright © 2011-2022 走看看