生产者—队列—消费者

1.问题建模

生产者制作 dryToast 放进队列,然后消费者 buttered 从队列中取出陌上黄油(然后放进队列,butter既是消费者,也是生产者);

1.1 详细设计

Toast类,有:

  1. 状态变量和ID;
  2. 改变状态的方法(从dry状态修改为buttered)状态;

LinkedBlockingQueue:存放吐司的队列,本例需要两个,因为陌上黄油后的Toast有作为了“产品”——其实也可以不用放进里边,仅仅是为了学习;

Toaster,生产Toast并放进队列中;

Buttered,从 dryToastQueue中获取吐司,调用吐司方法抹上酱,然后放进另一个队列(当然也可以直接消费);

ToastOMatic:驱动类,创建线程池并执行任务;

1.2 代码是吸纳
package design_pattern;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author 杜艮魁
 * @date 2018/3/25
 */

class Toast{
    int id;

    public enum STATUS{DYR,BUTTERED};

    STATUS status=STATUS.DYR;//初始化时为dry,即刚生产出来的状态

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

    public void buttered(){
        this.status=STATUS.BUTTERED;
    }

    @Override
    public String toString() {
        return "toast "+ id+":"+status.name();
    }
}

class ToastQueue extends LinkedBlockingQueue<Toast>{};

class Toaster implements Runnable{
    ToastQueue toastQueue;

    int count=0;//生产吐司数目计数器
    public Toaster(ToastQueue toastQueue) {
        this.toastQueue = toastQueue;
    }

    @Override
    public void run() {
        try{
            while(!Thread.interrupted()){
                Toast toast=new Toast(count++);
                System.out.println("put "+toast+"in toastQueue");
                toastQueue.put(toast);
            }
        }catch (InterruptedException e){
            System.out.println("Toaster stop");
        }
    }
}

class Buttered implements Runnable{
    ToastQueue toastQueue;
    ToastQueue butteredQueue;

    public Buttered(ToastQueue toastQueue, ToastQueue butteredQueue) {
        this.toastQueue = toastQueue;
        this.butteredQueue = butteredQueue;
    }

    @Override
    public void run() {
        try{
            while(!Thread.interrupted()){
                Toast toast=toastQueue.take();
                toast.buttered();
                butteredQueue.put(toast);
                System.out.println("take toast then buttered and put it in butteredQueue:"+toast);
            }
        }catch(InterruptedException e){
            System.out.println("Buttered out");
        }
    }
}

public class ProducerConsummerQueue {
    public static void main(String[] args) throws InterruptedException {
        ToastQueue dryQueue=new ToastQueue(),
                butteredQueue=new ToastQueue();

        ExecutorService executorService= Executors.newCachedThreadPool();
        executorService.execute(new Toaster(dryQueue));
        executorService.execute(new Buttered(dryQueue,butteredQueue));

        TimeUnit.MILLISECONDS.sleep(6);

        executorService.shutdownNow();
    }
}

posted on 2018-04-21 14:05  coderDu  阅读(168)  评论(0编辑  收藏  举报