1. 程式人生 > 其它 >投稿開獎丨輕量應用伺服器徵文活動(2月)獎勵公佈

投稿開獎丨輕量應用伺服器徵文活動(2月)獎勵公佈

wait\notify

package Thread.Demo10;

/**
 * 等待\喚醒,wait\notify
 * 消費者生產者模型--》利用緩衝區解決問題:管程法
 * @author liu
 */

//生產者,消費者,產品,緩衝區
public class ProductorModem {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}


//生產者
class Productor extends Thread {
    SynContainer container;

    public Productor(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        //生產了i只雞
        for (int i = 0; i < 100; i++) {
            container.push(new Chickden(i));
            System.out.println("生產了" + i + "只雞");
        }
    }
}

//消費者
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消費了--》" + container.pop().id + "只雞");
        }
    }
}


//產品
class Chickden {
    int id;//產品編號

    public Chickden(int id) {
        this.id = id;
    }
}


//緩衝區
class SynContainer {
    //需要一個容器大小
    Chickden[] chickdens = new Chickden[10];
    //容器計數器
    int count = 0;

    //生產者放入產品
    public synchronized void push(Chickden chickden) {
        //如果容器滿了,就需要等待消費
        if (count == chickdens.length) {
            //通知消費者消費,生產者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果沒滿,我們需要繼續丟入產品
        chickdens[count] = chickden;
        count++;
        //通知消費者消費
        this.notifyAll();
    }

    //消費者消費
    public synchronized Chickden pop() {
        //判斷能否消費
        if (count == 0) {
            //等待消費者生產
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消費
        count--;
        Chickden chickden = chickdens[count];
        //吃完了,通知生產者生產
        this.notifyAll();
        return chickden;
    }
}```