图解java多线程设计模式学习第五章Producer-Consumer模式

生产者消费者模式,生产者安全地将数据交给消费者。虽然仅是这样看似简单的操作,但当生产者和消费者以不同的线程运行时,两者之间的处理速度差异便会引起问题。例如,消费者想要获取数据,可数据还没有生成,或者生产者想要交付数据,而消费者的状态还无法接收数据等。一般来说,在该模式中,生产者和消费者都有多个,当然生产者和消费者有时也会只有一个。

有3位糕点师制作蛋糕并将其放到桌子上,然后有三个人来吃这些蛋糕。

糕点师(makerThread)制作蛋糕,并将其放到桌子(Table)上。

桌子上最多可放置3个蛋糕

如果桌子上已经放满三个蛋糕时糕点师还要再放置蛋糕,必须等到桌子上空出位置

客人取桌子上的蛋糕吃

客人按蛋糕被放置到桌子上的顺序来取蛋糕

当桌子上1个蛋糕都没有时,客人若要取蛋糕,必须等到桌子上新放置了蛋糕

package com.producerconsumer;

public class Table {
    private final String[] buffer;
    /** 下次put的位置 **/
    private int tail;
    /** 下次take的位置 **/
    private int head;
    /** buffer中的蛋糕个数 **/
    private int count;
    public Table( int count){
        this.buffer = new String [count];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
    }
    /**
     * 放置蛋糕
     * @param cake
     * @throws InterruptedException
     */
    public synchronized void put(String cake) throws InterruptedException{
        System.out.println(Thread.currentThread().getName() + " puts " +cake);
        while(count >= buffer.length){
            wait();
        }
        buffer[tail] = cake;
        tail = (tail + 1) % buffer.length;
        count++;
        notifyAll();
    }
    public synchronized String take() throws InterruptedException{
        while(count <= 0){
            wait();
        }
        String cake = buffer[head];
        head = (head + 1)% buffer.length;
        count --;
        notifyAll();
        System.out.println(Thread.currentThread().getName() + " takes " + cake);
        return cake;
    }
}

package com.producerconsumer;

import java.util.Random;

public class MakeeThread extends Thread{

    private final Random random;
    private final Table table;
    private static int id = 0;
    public MakeeThread(String name, Table table, long seed){
        super(name);
        this.table = table;
        this.random = new Random();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while(true){
                Thread.sleep(random.nextInt(1000));
                String cake = "[Cake NO." + nextId() + " by " + getName() + " ] " ;
                table.put(cake);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    private static synchronized int nextId() {
        // TODO Auto-generated method stub
        return id++;
    }
}

package com.producerconsumer;

import java.util.Random;

public class EaterThread extends Thread{

    private final Random random;
    private final Table table;
    public EaterThread(String name, Table table, long seed){
        super(name);
        this.table = table;
        this.random = new Random(seed);
    }
    @Override
    public void run() {
        try {
            while(true){
                String take = table.take();
                Thread.sleep(random.nextInt(1000));
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

package com.producerconsumer;

public class Main {

    public static void main(String[] args) {
        //创建一个能放置是三个蛋糕的桌子
        Table table = new Table(3);
        new MakeeThread("MakerThread-1", table, 31415).start();
        new MakeeThread("MakerThread-2", table, 92653).start();
        new MakeeThread("MakerThread-3", table, 58979).start();
        new EaterThread("EaterThread-1", table, 32384).start();
        new EaterThread("EaterThread-2", table, 62643).start();
        new EaterThread("EaterThread-3", table, 38327).start();
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值