多线程--消费者与生产者实例

多线程实例

1.消费者与生产者实例(管程法)

  • 产品、消费者、生产者、缓冲区
    • 产品,保证有一个唯一标识即可
    • 消费者继承Thread,注册缓冲区,从缓冲区消费
    • 生产者继承Thread,注册缓冲区,向缓冲区生产
    • 缓冲区确定容器大小,包含消费方法pop()、生产方法push()。处理线程问题
package com.wzh.thread;

/**
 * @author 75654
 *
 * 管程法:
 *      生产者,消费者,缓冲区
 *      生产者将生产物品放入缓冲区,消费者从缓冲区获取物品。
 *
 * 例:生产者生产鸡肉,消费消费鸡肉
 *      使用wait()、notifyAll()
 */
public class gcThread {
    public static void main(String[] args) {
        Cushion cushion = new Cushion();
        new Producer(cushion).start();
        new Consumer(cushion).start();
    }

}

/**
 * 产品--鸡肉 id
 */
class Chicken{
    private int id;

    public Chicken(){
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

/**
 * 生产者--生产鸡肉
 */
class Producer extends Thread{
    private Cushion cushion;

    public Producer(Cushion cushion) {
        this.cushion = cushion;
    }

    /**
     * 生产
     *      注意输出语句放在操作前面,避免输出紊乱
     */
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产鸡,编号" + i + "Id");
            cushion.push(new Chicken(i));
        }
    }
}

/**
 * 消费者--消费鸡肉
 */
class Consumer extends Thread {
    private Cushion cushion;

    public Consumer(Cushion cushion) {
        this.cushion = cushion;
    }

    /**
     * 消费
     */
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("吃了鸡编号:" + cushion.pop().getId());
        }
    }
}

/**
 * 缓冲区--存放鸡肉
 *      取出
 *      存放
 */
class Cushion{
    /**
     * 缓冲区大小,鸡肉存放位置标记
     */
    private Chicken[] chickens = new Chicken[10];
    private int count = 0;

    /**
     * 存入
     * @param chicken
     */
    public synchronized void push(Chicken chicken){
        if (count == chickens.length) {
            //生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //存入缓冲区,总数增加
        chickens[count] = chicken;
        count++;

        //通知消费者消费
        this.notifyAll();
    }

    /**
     * 取出
     */
    public synchronized Chicken pop(){
        if (count == 0) {
            //消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //缓冲区减少,取出消费的鸡
        count--;
        Chicken chicken = chickens[count];

        //通知消费者消费
        this.notifyAll();
        return chicken;
    }

}
posted @ 2023-01-31 21:13  mengdreams  阅读(29)  评论(0编辑  收藏  举报