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();
    }
    }
    }

    }
    心之何如,有似万丈迷津,遥亘千里,其中并无舟子可以渡人,除了自渡,他人爱莫能助。
  • 相关阅读:
    6.素数和(素数的判断)
    6.素数和(素数的判断)
    5.明明的随机数(桶排序经典例题)
    5.明明的随机数(桶排序经典例题)
    5.明明的随机数(桶排序经典例题)
    5.明明的随机数(桶排序经典例题)
    Algs4-1.2.11根据Date的API实现一个SmartDate类型
    Algs4-1.2.10编写一个类VisualCounter
    Algs4-1.2.9使用Counter统计BinarySearch检查的key个数
    Algs4-1.2.8引用型变量赋值-数组复制
  • 原文地址:https://www.cnblogs.com/s88888888/p/13099361.html
Copyright © 2011-2022 走看看