关于消费者.生产者,缓冲区的简单java实现

来源:互联网 发布:好听的名字知乎 编辑:程序博客网 时间:2024/05/29 14:34
package com.huawei.concurrent.test;

import java.util.LinkedList;

class Consumer extends Thread

    private ProductTable productTable;

    public Consumer(ProductTable productTable)
    {
        this.productTable = productTable;
    }

    public void run()
    {
        for (int i = 1; i <= 10; i++)
        {
            productTable.getProduct();
        }
    }
}

class Producer extends Thread
{

    private Product p;
    private ProductTable productTable;

    public Producer(ProductTable productTable, Product p)
    {
        this.productTable = productTable;
        this.p = p;
    }

    public void run()
    {
       for (int product = 1; product <= 10; product++)
        {
            productTable.addProduct(p);
        }
    }
}

class Product
{
    private int id;
    private String value;

    public Product(int id, String value)
    {
        this.id = id;
        this.value = value;
    }

    public int getId()
    {
        return id;
    }

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

    public String getValue()
    {
        return value;
    }

    public void setValue(String value)
    {
        this.value = value;
    }
}

class ProductTable
{
    private final int maxSize;
    private LinkedList<Product> products = new LinkedList<Product>();

    public ProductTable(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public synchronized void addProduct(Product product)
    {
        while (products.size() >= maxSize)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {}
        }

        products.addLast(product);
        System.out.println(product.getId() + " added");
        notify();
    }

    public synchronized Product getProduct()
    {
        while (products.size() <= 0)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {}
        }

        Product product = (Product) products.removeFirst();
        System.out.println(product.getId() + " removed");
        notify();

        return product;
    }
}

public class MainT
{
    public static void main(String[] args)
    {
        Product a = new Product(1, "a");
        ProductTable queue = new ProductTable(5);
        Producer producera = new Producer(queue, a);
        Consumer consumer = new Consumer(queue);
        new Thread(producera).start();
        new Thread(consumer).start();
    }

}

原创粉丝点击