Java实现生产者与消费者

来源:互联网 发布:主力净买入指标源码 编辑:程序博客网 时间:2024/05/18 00:32

生产者与消费者的线程实现问题分析可知:问题含有产品对象,产品池对象,消费者,生产者对象

产品对象

public class Product {int id;String name;Product(){}Product(int id,String name){this.name=name;this.id=id;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
产品池对象

public class Container {ArrayList<Product> products = new ArrayList<Product>();int max=10;public synchronized void push(Product product) {if(products.size()==max){notify();     System.out.println("产品富足,等待消费");     try {wait();} catch (InterruptedException e) {e.printStackTrace();}}products.add(product);notify();}public synchronized Product pop() {if(products.size()==0){     System.out.println("产品匮乏,等待生产");     try {wait();} catch (InterruptedException e) {e.printStackTrace();}}Product product=products.get(products.size()-1);products.remove(products.size()-1);notify();return product;}}

消费者
public class Consumer implements Runnable {  private String consumerName;      //保留有缓冲区对象的引用,以便消费产品      private Container container;            public Consumer(String consumerName, Container container) {          this.consumerName = consumerName;          this.container = container;      }        public void run() {          while(true){              System.out.println("消费者"+consumerName+"已经消费"+container.pop());              try {                  Thread.sleep(2000);              } catch (InterruptedException e) {                  e.printStackTrace();              }          }        }  }
生产者
public class Producter implements Runnable{private String producterName;        //  保留有缓冲区对象的引用,以便将生产的产品放入缓冲区      private Container container;            public Producter(String producterName, Container container) {          this.producterName = producterName;          this.container = container;      }      public void producterProduct(){          //生产产品,并放入到仓库中          int i=0;          while(true){              i++;              Product product=new Product(i,"新产品");              container.push(product);              System.out.println(producterName+"生产了");              try {                  Thread.sleep(2000);              } catch (InterruptedException e) {                  return;              }          }      }public void run() {producterProduct();}    }
调用函数
public class Main {public static void main(String[] args) {Container container=new Container();Consumer con=new Consumer("消费", container);Producter producter=new Producter("新产品",container);Thread t1=new Thread(con);Thread t2=new Thread(producter);t1.start();t2.start();}}





0 0