• 生产者消费者问题


    public class Depot {
        
        int capacity ;
        int size;
        public Depot(int capacity){
            this.capacity = capacity;
            this.size = 0;
        }
        
        public synchronized void produce(int val){
            try{
                int left = val;//val可能 > capacity,因此需要多次生产
                while(left > 0){//
                    while(size >= capacity){//当库存已满时,生产者需要将自己挂起,并唤醒消费者,让消费者来消费。
                        wait();
                    }
                    int inc = (size + left) > capacity ? (capacity - size) : left;//每次生产的数量与capacity有关
                    size += inc;
                    left -= inc;
                    System.out.printf("%s produce(%3d) --> left=%3d, inc=%3d, size=%3d
    ", Thread.currentThread().getName(), val, left, inc, size);
                    notifyAll();//唤醒消费者来消费
                }
            }catch(Exception e){
            }
        }
        
        public synchronized void consum(int val){
            try{
                int left = val;
                while(left > 0){
                    while(size <= 0){//当库存为0时,消费者将自己挂起,通知生产者生产
                        wait();
                    }
                    int dec = (size > left) ? left : size;//同上
                    size -= dec;
                    left -= dec;
                    System.out.printf("%s consume(%3d) --> left=%3d, dec=%3d, size=%3d
    ", Thread.currentThread().getName(), val, left, dec, size);
                    notifyAll();
                }
            }catch(Exception e){}
        }
        
    }

    生产者& 消费者对工厂的访问:

    public class ConsumerAndProducer {
        public static void main(String[] args) {
            Depot depot = new Depot(100);
            Producer pro = new Producer(depot);
            Consumer con = new Consumer(depot);
            pro.produce(120);
            pro.produce(150);
            con.consum(110);
            con.consum(120);
        }
    }
    
    class Consumer {
        Depot depot;
        public Consumer(Depot depot){
            this.depot = depot;
        }
        public void consum(final int val){
            new Thread(){
                public void run(){
                    depot.consum(val);
                }
            }.start();
        }
    }
    class Producer{
        Depot depot;
        public Producer(Depot depot){
            this.depot = depot;
        }
        public void produce(final int val){
            new Thread(){
                public void run(){
                    depot.produce(val);
                }
            }.start();
        }
    }

    多线程相关

  • 相关阅读:
    bzoj 3747: [POI2015]Kinoman
    bzoj 3123: [Sdoi2013]森林
    bzoj 1901: Zju2112 Dynamic Rankings
    poj 1741 Tree
    bzoj 2152: 聪聪可可
    bzoj 2599: [IOI2011]Race
    bzoj 3697: 采药人的路径
    bzoj 2728: [HNOI2012]与非
    bzoj 2115: [Wc2011] Xor
    bzoj 3143: [Hnoi2013]游走
  • 原文地址:https://www.cnblogs.com/huntfor/p/3986266.html
Copyright © 2020-2023  润新知