2020年9月12日 生产者与消费者问题

package com.guigu.test14;

public class Test14 {
    public static void main(String[] args) {
        FoodTable f = new FoodTable();
        Cook c = new Cook("厨子",f);
        Waiter w = new Waiter("服务员", f);
        
        c.start();
        w.start();
    }
}
class FoodTable{
    private static final int MAX = 3;
    private int count;
    
    public synchronized void put(){
        if(count>=MAX){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count++;
        System.out.println(Thread.currentThread().getName()+"放了一盘菜,剩余:" + count);
        this.notify();    
    }
    public synchronized void take(){
        if(count<=0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        System.out.println(Thread.currentThread().getName()+"取走一盘菜,剩余:" + count);
        this.notify();
    }
    
}
class Cook extends Thread{
    private FoodTable f;
    
    public Cook(String name, FoodTable f) {
        super(name);
        this.f = f;
    }

    @Override
    public void run() {
        while(true){
            f.put();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}
class Waiter extends Thread{
    private FoodTable f;
    
    public Waiter(String name, FoodTable f) {
        super(name);
        this.f = f;
    }

    @Override
    public void run() {
        while(true){
            f.take();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}

 

posted @ 2020-09-12 16:02  窦云鹏  阅读(129)  评论(0编辑  收藏  举报