生产者消费者

介绍:生产者消费者模式其实就是我们生活过程中的示例,比如我一个工厂,要求库存不能大于5,那么生产和消费一定都要同步,不能过度生产,也不能过度消费。要同时报错库存的容量恒定在0~5之间,不能犯规。这样就涉及了同用资源的问题,万一同时生产同时消费这种情况很难处理,所以我使用同步。上锁确保同一时间只能一个操作。代码如下:

import java.util.ArrayList;
/**
 * 定义一个容器,处理生产者消费者,同时要有指针标识,容器要有固定大小
 * @author Administrator
 *
 */
public class Factory {
    int index=0;
    ArrayList<Object> Array=new ArrayList<>(); //定义最大长度为5个吧;
    
    public synchronized void product(){
        while(Array.size()==5){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        Array.add(new Object());
        index++;
        System.out.println("生产后容器实际大小为"+Array.size());
    }
    
    public synchronized void comsume(){
        while(Array.size()==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        Array.remove(0);
        index--;
        System.out.println("消费后容器实际大小为"+Array.size());
    }

}

测试用例:

public class Test {

    public static void main(String[] args) {
        Factory factory=new Factory();
        Product1 product1=new Product1(factory);
        Comsume1 comsume1=new Comsume1(factory);
        product1.start();
        comsume1.start();
    }

}
class Product1 extends Thread{
    private Factory factory;
    public Product1(Factory factory) {
        this.factory=factory;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            try {
                factory.product();
                if(i==10){
                    Thread.currentThread().sleep(30000);
                }
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Comsume1 extends Thread{
    private Factory factory;
    public Comsume1(Factory factory) {
        this.factory=factory;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            try {
                factory.comsume();
                Thread.currentThread().sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

同时注意一下这里面的this,所代表的其实都是test里面 同一个factory.当两个线程跑起来由于生产的速度是比较块的,当库存大于5的时候线程阻塞,同时让出

cpu时间片,消费者就抢过去,消费完了就唤醒线程,然后这两个线程继续争夺时间片,如此循环。

原文地址:https://www.cnblogs.com/lq625424841/p/7211608.html