zoukankan      html  css  js  c++  java
  • 生产者消费者模型

    1,仓库类
    public class WareHouse {

    private ArrayList<String> list = new ArrayList<>();

    private Integer i = 0;
    /**
    * 向集合中添加元素
    */
    public synchronized String add(){
    if(list.size()<20){
    list.add(i+++"");
    }else{
    //return;
    try {
    this.notifyAll();//唤醒全部线程,可根据设置的优先级唤醒顺序
    this.wait();//进入等待(阻塞)
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    if(list.size()>0){
    return list.get(list.size()-1);
    }else{
    return "";
    }
    }

    /**
    * 从集合中取出元素
    */
    public synchronized String get(){
    String name = "";
    if(list.size()>0){
    name = list.remove(0);
    }else{
    //return;
    try {
    this.notifyAll();//唤醒全部线程,可根据设置的优先级唤醒顺序
    this.wait();//进入等待(阻塞)
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    return name;
    }
    }

    2,消费者类
    public class Consumer extends Thread{

    private String name;

    private WareHouse house;


    public Consumer(String name,WareHouse house){
    this.name = name;
    this.house = house;
    }

    public void run(){
    String houseName = null;
    while(true){
    houseName = house.get();
    System.out.println(this.name+"拿走了一件货物。。"+houseName);
    try {
    this.sleep(400);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    3,生产者类
    public class Producer extends Thread{

    private String name;

    private WareHouse house;

    public Producer(String name,WareHouse house){
    this.name = name;
    this.house = house;
    }

    public void run(){
    String houseName = null;
    while(true){
    houseName = house.add();
    System.out.println(this.name+"生产了一件货物。。"+houseName);
    try {
    this.sleep(200);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }

    }
    心之何如,有似万丈迷津,遥亘千里,其中并无舟子可以渡人,除了自渡,他人爱莫能助。
  • 相关阅读:
    cbitmap 获取RGB
    存稿
    VC单选按钮控件(Radio Button)用法(转)
    MFC文档视图中窗口切换 (2012-05-11 18:32:48)
    MFC 结束线程
    vs2010调试运行时弹出对话框:系统找不到指定文件
    fatal error C1189: #error : This file requires _WIN32_WINNT to be #defined at least to 0x0403. Value 0x0501 or higher is recommended.
    自定义消息
    数据分析与可视化--matplotlib
    数据分析与可视化--pandas
  • 原文地址:https://www.cnblogs.com/s88888888/p/13099361.html
Copyright © 2011-2022 走看看