Java——多生产者 多消费者

//使用jdk1.5的多线程实现方式实现可以同时多生产多消费的功能
//跟之前的博客类似,就是多了个容器,从而实现多生产多消费的功能
import java.util.concurrent.locks.*;
//描述产品
class Clothes{
    //产品名称
    private String name;
    //产品价格
    private double price;
    //存放产品的容器
    private Clothes[] arr = new Clothes[100];
    //创建一把锁
    private Lock lock = new ReentrantLock();
    //创建和锁绑定的Condition对象,控制生产线程
    private Condition pro = lock.newCondition();
    //创建和锁绑定的Condition对象,控制消费线程
    private Condition con = lock.newCondition();
    //生产使用的下标
    private int propointer;
    //消费使用的下标
    private int conpointer;
    //记录产品数量
    private int count;

    public Clothes(){}

    public Clothes(String name,double price){
        this.name = name;
        this.price = price;
    }
    //生产功能
    public void produce(){
        lock.lock();
        try{
            //先判断该不该生产,当容器满的时候不能生产
            while(count==arr.length){
                try{pro.await();}catch(InterruptedException e){e.printStackTrace();}
            }
            arr[propointer] = new Clothes("衬衣",99.99);
            System.out.println(Thread.currentThread().getName()+"...生产了..."+arr[propointer]+"..."+count);
            count++;//数量+1
            if(++propointer==arr.length)
                propointer = 0;
            con.signal();
        }
        finally{
            lock.unlock();
        }
    }
    //消费功能
    public void consume(){
        lock.lock();
        try{
            //先判断该不该消费,当商品数量为0的时候不能消费
            while(count==0){
                try{con.await();}catch(InterruptedException e){e.printStackTrace();}
            }
            Clothes yifu = arr[conpointer];
            System.out.println(Thread.currentThread().getName()+"...消费了..."+yifu);
            count--;
            if(++conpointer==arr.length)
                conpointer = 0;
            pro.signal();
        }
        finally{
            lock.unlock();
        }
    }

        public String toString(){
            return name+","+price;
        }
}
//生产任务
class Producer implements Runnable{
    private Clothes clo;
    public Producer(Clothes clo){
        this.clo = clo;
    }
    public void run(){
        while(true){
            clo.produce();
        }
    }
}
//消费任务
class Consumer implements Runnable{
    private Clothes clo;
    public Consumer(Clothes clo){
        this.clo = clo;
    }
    public void run(){
        while(true){
            clo.consume();
        }
    }
}


class test{
    public static void main(String[] args){
        Clothes clo = new Clothes();

        Producer producer = new Producer(clo);
        Consumer consumer = new Consumer(clo);

        Thread t1 = new Thread(producer);
        Thread t2 = new Thread(producer);

        Thread t3 = new Thread(consumer);
        Thread t4 = new Thread(consumer);

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

你可能感兴趣的:(java知识点)