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

    /**

    • 生成者,消费者,产品,容器
    • @author Administrator

    */
    public class ProducerConsumer {
    public static void main(String[] args) {
    Container ct = new Container();//生成容器
    //生产者消费者拥有同一个容器
    Producer p = new Producer(ct);
    Consumer c = new Consumer(ct);
    Thread t1 = new Thread(p);//生产者线程
    Thread t2 = new Thread(c);//消费者线程
    //Thread t3 = new Thread(c);//消费者线程
    //Thread t4 = new Thread(c);//消费者线程
    t1.start();
    t2.start();
    }
    }
    //1.先定义产品类
    class Product{
    //产品id
    int id ;
    Product(int id){
    this.id = id;
    }
    public String toString(){
    return "product"+id;
    }
    }
    //2.再定义容器类
    class Container{
    //定义容器的容量
    Product [] p = new Product[5];
    //容器当前存放产品位置
    int index =0;
    //往容器里放东西
    public synchronized void put(Product pro){
    while(indexp.length){
    try {
    //生产满了要等待消费
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    //唤醒生产者
    this.notify();
    p[index] = pro;
    System.out.println("生产了"+pro);
    index++;
    }
    //从容器中拿走产品
    public synchronized Product get(){
    //因为index位置没有产品,所以要先--
    while(index
    0){
    try {
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    this.notify();
    index--;
    Product p2 = p[index];
    System.out.println("消费了"+p2);
    return p2;
    }
    }
    //定义生产者实现了Runnable接口
    class Producer implements Runnable{
    Container c = null;
    Producer(Container c){
    this.c = c;
    }
    @Override
    public void run() {
    //生产了30个产品
    for(int x = 1;x<=30;x++){
    Product p = new Product(x);
    //往里面放产品
    c.put(p);
    try {
    Thread.sleep(100);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    }
    

    }
    //4.定义消费者从里面拿东西也实现Runnable接口
    class Consumer implements Runnable{
    Container c = null;
    Consumer(Container c){
    this.c = c;
    }
    @Override
    public void run() {
    for(int x = 1;x<=30;x++){
    //从里面拿产品
    c.get();
    try {
    Thread.sleep(200);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    	}
    
    }
    

    }

  • 相关阅读:
    2015抢票记事
    Provide your license server administrator with the following information.error code =-42,147
    微信支付现金红包接口
    SQL Server 触发器
    SQL增删查改注意的事项
    SQL while循环
    SQL SERVER 中is null 和 is not null 将会导致索引失效吗?
    HTML中head里的内容经浏览器解析后全到body里了
    sqLSERVER 计划缓存
    通用分页存储过程
  • 原文地址:https://www.cnblogs.com/king8/p/11040313.html
Copyright © 2011-2022 走看看