日志文章

2019-12-26 aflfte2011

协作模型:管程法

package com.aflfte.cooperation;
/**
 * 协作模型:管程法
 * 管程法模式(生产者与消费者模式)
 * 借助缓冲区实现数据的快速读写操作
 *
 * @author root
 *
 */
public class CoTest01 {
    public static void main(String[] args) {
        SynContainer container=new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Productor extends Thread{
    SynContainer container;
    public Productor(SynContainer container) {
        super();
        this.container = container;
    }

    public void run() {
        //开始生产
        for(int i=0;i<100;i++) {
            System.out.println("生产"+i+"个产品");
            container.push(new Product(i));
        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer container;
    
    public Consumer(SynContainer container) {
        super();
        this.container = container;
    }

    public void run() {
        //开始消费
        for(int i=0;i<100;i++) {
            System.out.println("买走"+container.pop().id+"个产品");
        }
        
    }
}
//缓冲区
class SynContainer{
    Product[] pros=new Product[10];
    int count=0;
    //存储  生产
    public synchronized void push(Product pro) {
        //何时可以存储数据  只要容器有空间不可存数据
        if(count==pros.length) {//如果容器没有空间
            try {
                this.wait();//线程阻塞 等待写入  等待读取通知
            } catch (InterruptedException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        
        pros[count]=pro;
        count++;
        //存在数据可以唤醒读取了
        this.notifyAll();
    }
    //读取
    public synchronized Product pop() {
        //何时读取 判断容器中有没有数据 有就读取  没有就等待
        if(count==0) {//如果没有数据
            try {
                this.wait();//线程阻塞 等待读取 写入通知解除
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Product pro=pros[count];
        this.notifyAll();//容器中有空间了  唤醒写入数据
        return pro;
    }
    
}
//产品
class Product{
    int id;

    public Product(int id) {
        super();
        this.id = id;
    }
    
}

« 协作模式:信号灯法 | 死锁的产生与解决方案»