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

    	}
    
    }
    

    }

  • 相关阅读:
    JS 中如何判断字符串类型的数字
    使用script的src实现跨域和类似ajax效果
    JS跨域(ajax跨域、iframe跨域)解决方法及原理详解(jsonp)
    IOS上架截屏 屏幕快照
    IOS 证书失效
    80端口占用
    PHP环境 PDOException PDOException: could not find driver
    分布式部署
    AES 加密算法 跨语言
    AES 加密填充 PKCS #7
  • 原文地址:https://www.cnblogs.com/king8/p/11040313.html
Copyright © 2011-2022 走看看