Java multithreading - concurrent collaboration (producer consumer model)

For multithreaded programs, regardless of any programming language, the producer and consumer model is the most classic. Like learning every programming language, Hello World! are the most classic examples.

In fact, it should be precisely the "producer-consumer-warehouse" model. Without the warehousing, the producer-consumer model would be unconvincing.
For this model, the following points should be clarified:
1. The producer only produces when the warehouse is not full, and stops production when the warehouse is full.
2. Consumers can only consume when there are products in the warehouse, and wait when the warehouse is empty.
3. When consumers find that there is no product available in the warehouse, they will notify the producer to produce.
4. When producers produce consumable products, they should notify waiting consumers to consume them.

copy code
package cn.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * java multithreading simulates producer consumer problem
 *
 * ProducerConsumer is the main class, Producer producer, Consumer consumer, Product product, Storage warehouse
 *
 * @author Lin Jiqin
 * @version 1.0 2013-7-24 下午04:49:02
 */
public class ProducerConsumer {
    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Storage s = pc.new Storage();

        ExecutorService service = Executors.newCachedThreadPool();
        Producer p = pc. new Producer("Zhang San" , s);
        Producer p2 = pc.new Producer("李四", s);
        Consumer c = pc.new Consumer("王五", s);
        Consumer c2 = pc.new Consumer("老刘", s);
        Consumer c3 = pc.new Consumer("老林", s);
        service.submit(p);
        //service.submit(p2);
        service.submit(c);
        service.submit(c2);
        service.submit(c3);
        
    }

    /**
     * Consumer
     *
     * @author Lin Jiqin
     * @version 1.0 2013-7-24 下午04:53:30
     */
    class Consumer implements Runnable {
        private String name;
        private Storage s = null;

        public Consumer(String name, Storage s) {
            this.name = name;
            this.s = s;
        }

        public void run() {
            try {
                while (true) {
                    System.out.println(name + "Ready to consume product." );
                    Product product = s.pop();
                    System.out.println(name + "已消费(" + product.toString() + ").");
                    System.out.println("===============");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }

        }

    }

    /**
     * Producer
     *
     * @author Lin Jiqin
     * @version 1.0 2013-7-24 下午04:53:44
     */
    class Producer implements Runnable {
        private String name;
        private Storage s = null;

        public Producer(String name, Storage s) {
            this.name = name;
            this.s = s;
        }

        public void run() {
            try {
                while (true) {
                    Product product = new Product(( int ) (Math.random() * 10000)); // Generate 0~9999 random integer 
                    System.out.println(name + "Ready to produce(" + product.toString() + ") ." );
                    s.push(product);
                    System.out.println(name + "已生产(" + product.toString() + ").");
                    System.out.println("===============");
                    Thread.sleep(500);
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

        }
    }

    /**
     * Warehouse to store products
     *
     * @author Lin Jiqin
     * @version 1.0 2013-7-24 04:54:16 PM
      */ 
    public  class Storage {
        BlockingQueue<Product> queues = new LinkedBlockingQueue<Product>(10);

        /**
         * Production
         *
         * @param p
         * product
         * @throws InterruptedException
         */
        public void push(Product p) throws InterruptedException {
            queues.put(p);
        }

        /**
         * Consumption
         *
         * @return product
         * @throws InterruptedException
         */
        public Product pop() throws InterruptedException {
            return queues.take();
        }
    }

    /**
     * product
     *
     * @author Lin Jiqin
     * @version 1.0 2013-7-24 04:54:04 PM
      */ 
    public  class Product {
         private  int id;

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

        public String toString() { // Override toString method 
            return "Product:" + this .id;
        }
    }

}
copy code
copy code
Zhang San is ready for production (Product: 3359 ).
Zhang San has produced (Product: 3359 ).
 ===============
Lao Liu is ready to consume products.
Wang Wu has consumed (product: 3359 ).
 ===============
Wang Wu is ready to consume the product.
Zhang San ready for production (Product: 1863 ).
Zhang San has produced (Product: 1863 ).
 =============== 
Lao Lin has consumed (Product: 1863 ).
 ===============
Lao Lin ready to consume product.
Zhang San is ready for production (Product: 5424 ).
Zhang San has produced (Product: 5424 ).
Lao Liu has consumed (product: 5424 ).
 ===============
============== 
Zhang San is ready for production (Product: 6290 ).
张三已生产(产品:6290).
===============
老刘准备消费产品.
王五已消费(产品:6290).
===============
张三准备生产(产品:990).
张三已生产(产品:990).
===============
老林已消费(产品:990).
===============
王五准备消费产品.
张三准备生产(产品:1971).
老林准备消费产品.
老刘已消费(产品:1971).
===============
张三已生产(产品:1971).
===============
张三准备生产(产品:5622).
老刘准备消费产品.
张三已生产(产品:5622).
===============
王五已消费(产品:5622).
===============
王五准备消费产品.
张三准备生产(产品:6570).
张三已生产(产品:6570).
===============
老林已消费(产品:6570).
===============
老林准备消费产品.
张三准备生产(产品:17).
老刘已消费(产品:17).
===============
张三已生产(产品:17).
===============
老刘准备消费产品.
张三准备生产(产品:7962).
张三已生产(产品:7962).
===============
王五已消费(产品:7962).
===============
王五准备消费产品.
张三准备生产(产品:3200).
张三已生产(产品:3200).
===============
老林已消费(产品:3200).
===============
老林准备消费产品.
张三准备生产(产品:7234).
Zhang San has produced (product: 7234 ).
 =============== 
Lao Liu has consumed (product: 7234 ).
 ===============
Lao Liu is ready to consume products.
Zhang San is ready for production (Product: 6486 ).
Zhang San has produced (Product: 6486 ).
 =============== 
Wang Wu has consumed (Product: 6486 ).
 =============== 
Zhang San is ready for production (Product: 5436 ).
Wang Wu is ready to consume the product.
Wang Wu has consumed (product: 5436 ).
 ===============
copy code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326228656&siteId=291194637