java生产者消费者

生产者消费者模型是并发编程中比较经典的问题,其他的不多说,直接给出代码
线程同步采用synchronized,当然了,使用ReentrantLock或者Semaphore进行线程之间的通信也完全可以;

public class StringTest {
    public static void main(String[] args) {

        /*生产者消费者模型*/
        Product product = new Product();
        Thread produce = new Thread(new ProduceProduct(product));
        produce.setName("生产者1 ");
        Thread comsume = new Thread(new ConsumeProduct(product));
        comsume.setName("消费者1 ");
        Thread comsume2 = new Thread(new ConsumeProduct(product));
        comsume2.setName("消费者2 ");
        produce.start();
        comsume.start();
        comsume2.start();
        }

    }

    static class Product{

        private int max_product = 10;
        private int min_product = 0;
        private int product = 0;
        public Product(int max_product){
            this.max_product = max_product;
        }
        public Product(){
        }

        public synchronized void produceProduct(){
            if (this.product >= max_product) {
                try{
                    System.out.println("产品已经足够,请稍等");
                    wait();
                }catch (Exception e) {
                }
                return;
            }
            product++;
            System.out.println(Thread.currentThread().getName() + " 生产了第:" + product + "个产品");
            notifyAll();
        }
        public synchronized void comsumeProduct(){
            if (this.product <= min_product) {
                try{
                    System.out.println("产品不够了,请稍等");
                    wait();
                }catch (Exception e) {
                }
                return;
            }
            System.out.println(Thread.currentThread().getName() + "消费了第:" + product + " 个产品");
            product--;
            notifyAll();
        }
    }

    static class ConsumeProduct implements Runnable{

        private Product product;
        public ConsumeProduct(Product product) {
            this.product = product;
        }
        @Override
        public void run() {
            System.out.println("开始消费产品");
            while(true){
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                product.comsumeProduct();
            }
        }

    }

    static class ProduceProduct implements Runnable{
        private Product product;
        public ProduceProduct(Product product) {
            this.product = product;
        }
        @Override
        public void run() {
            System.out.println("开始生产产品");
            while (true) {
                try{
                    Thread.sleep(1000);
                }catch (Exception e) {
                }
                product.produceProduct();
            }
        }

    }
}

你可能感兴趣的:(JAVA)