[the road to full stack] java basic course 4: producer consumer issues (20190614v1.1)

Time:2019-12-7

Welcome to java basic course

Blog address: https://segmentfault.com/a/11
This series of articles will mainly focus on some basic knowledge points of Java, which are summarized in ordinary times. No matter you are new to Java development rookie or senior people in the industry, you hope to bring some help to your peers. If you have any questions, please leave a message or add QQ: 243042162.

Message:
Nan Rendong, the father of “Tianyan”, has no distractions, burning up life for the “Tianyan” in China between the mountains. It looks like a “big pot”. Tianyan is the largest and most sensitive single port radio telescope in the world, which can receive electromagnetic signals 10 billion light-years away. Nanrendong chief engineer is dedicated to pursuing the spirit of scientific dream, which will encourage generations of science and technology workers to continue to strive and bravely climb the world’s science and technology peak. As it practitioners, we need to keep up with the pace of the times, step through the mediocrity, and build a dream for science and technology all our lives.

Producer consumer issues

1. background

Producer consumer problem, also known as bounded buffer problem, is a classic case of multithreading synchronization problem. The producer generates a certain amount of data into the buffer, and then repeats the process; at the same time, the consumer consumes the data in the buffer. Producers and consumers must keep synchronization, to ensure that producers do not put data when the buffer is full, and consumers do not consume data when the buffer is empty. Incomplete solutions are prone to deadlock, and the process is waiting to wake up.

2. conditions

  • The producer only produces when the warehouse is not full, and stops production when the warehouse is full
  • Producers should inform waiting consumers to consume when they produce consumable products
  • Consumers can only consume when there are products in the warehouse, and wait when the warehouse is empty
  • Consumers will inform producers when they find that there is no product available for consumption

3. Implementation mode

  • Wait() / notify() method
  • Await() / signal() method
  • BlockingQueue blocking queue method
  • Semaphore method
  • PipedInputStream / PipedOutputStream

The following is mainly for the code implementation of the first three methods

(1) wait() / notify() method

public class ProducerMain {

    private static Integer count=0;
    private final Integer full=10;
    private static String LOCK="LOCK";

    class  Producer implements Runnable{

        @Override
        public void run() {
//            for(int i=0;i<10;i++){
//                try {
//                    Thread.sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
            synchronized (LOCK){
                while(count==full){
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
                count++;
                System. Out. Println (thread. Currentthread(). Getname() + "produced by the producer, currently produced in total:" + count);
                LOCK.notifyAll();
            }
        }
    }
    class Consumer implements Runnable{

        @Override
        public void run() {
            synchronized (LOCK){
                while (count==0){
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                count--;
                System. Out. Println (thread. Currentthread(). Getname() + "producer consumption, total remaining at present:" + count);
                LOCK.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        ProducerMain producer = new ProducerMain();
        new Thread(producer.new Producer()).start();
        new Thread(producer.new Consumer()).start();
        new Thread(producer.new Producer()).start();
        new Thread(producer.new Consumer()).start();
        new Thread(producer.new Producer()).start();
        new Thread(producer.new Consumer()).start();
        new Thread(producer.new Producer()).start();
        new Thread(producer.new Consumer()).start();
    }
}

Output result

Thread-0 is produced by the producer. At present, the total production is: 1
Thread-5 producer consumption, total remaining: 0
Thread-2 is produced by the producer, and now the total production is: 1
Thread-7 producer consumption, total remaining: 0
Thread-6 is produced by the producer, and now the total production is: 1
Thread-1 producer consumption, total remaining: 0
Thread-4 is produced by the producer, and now the total production is: 1
Thread-3 producer consumption, total remaining: 0

(2) await() / signal() method

public class ReentrantLockDemo {
    private static Integer count = 0;
    private final Integer FULL = 10;
    final Lock lock = new ReentrantLock();
    final Condition NotFull = lock.newCondition();
    final Condition NotEmpty = lock.newCondition();

    class Producer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                lock.lock();
                try {
                    while (count == FULL) {
                        try {
                            NotFull.await();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    count++;
                    System.out.println(Thread.currentThread().getName()
                            +"+ count" for producer production;
                    NotEmpty.signal();
                } finally {
                    lock.unlock();
                }

            }
        }
    }

    class Consumer implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                lock.lock();
                try {
                    while (count == 0) {
                        try {
                            NotEmpty.await();
                        } catch (Exception e) {
                            // TODO: handle exception
                            e.printStackTrace();
                        }
                    }
                    count--;
                    System.out.println(Thread.currentThread().getName()
                            +"Consumer consumption, now there are" + count);
                    NotFull.signal();
                } finally {
                    lock.unlock();
                }

            }

        }

    }

    public static void main(String[] args) throws Exception {
        ReentrantLockDemo hosee = new ReentrantLockDemo();
        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();
        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();

        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();
        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();
    }
}

Output result

Thread-0 is produced by producers, and there are 1 in total at present
Thread-2 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-7 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-2 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-6 is produced by producers, with a total of 2
Thread-7 consumer spending, currently 1 in total
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-2 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-7 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-2 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-7 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-2 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-6 is produced by producers, with a total of 2
Thread-7 consumer spending, currently 1 in total
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-0 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-7 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-0 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-6 is produced by producers, with a total of 2
Thread-7 consumer spending, currently 1 in total
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-0 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-6 is produced by producers, with a total of 2
Thread-7 consumer spending, currently 1 in total
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-0 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-6 is produced by producers, with a total of 2
Thread-7 consumer spending, currently 1 in total
Thread-4 is produced by producers, and there are currently 2
Thread-5 consumer spending, currently 1 in total
Thread-3 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-2 is produced by producers, and there are 2 in total at present
Thread-1 consumer consumption, currently 1 in total
Thread-6 is produced by producers, with a total of 2
Thread-7 consumer spending, currently 1 in total
Thread-5 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0

(3) blocking queue

public class BlockingQueueMain {
    private static Integer count = 0;
    final BlockingQueue<Integer> bq = new ArrayBlockingQueue<Integer>(10);
    class Producer implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    bq.put(1);
                    count++;
                    System.out.println(Thread.currentThread().getName()
                            +"+ count" for producer production;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    class Consumer implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                try {
                    bq.take();
                    count--;
                    System.out.println(Thread.currentThread().getName()
                            +"Consumer consumption, now there are" + count);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) throws Exception {
        BlockingQueueMain hosee = new BlockingQueueMain();
        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();
        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();

        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();
        new Thread(hosee.new Producer()).start();
        new Thread(hosee.new Consumer()).start();
    }
}

Output result

Thread-1 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-0 is produced by the producer. There are 0 in total at present
Thread-5 consumer consumption, currently 0
Thread-3 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-6 is produced by producers, and there are 1 in total at present
Thread-7 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-1 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-6 is produced by the producer, with a total of 0
Thread-7 consumer consumption, currently 0
Thread-4 is produced by the producer, with a total of 0
Thread-1 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-7 consumer consumption, currently 0
Thread-4 is produced by a producer, with a total of 1
Thread-1 consumer consumption, currently 0
Thread-0 is produced by producers, and there are 1 in total at present
Thread-5 consumer consumption, currently 0
Thread-2 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-7 consumer consumption, currently 0
Thread-4 is produced by producers, and there are currently 2
Thread-0 is produced by producers, and there are 1 in total at present
Thread-1 consumer consumption, currently 0
Thread-5 consumer spending, currently 1 in total
Thread-2 is produced by a producer, with a total of 1
Thread-3 consumer consumption, currently 0
Thread-6 is produced by producers, and there are 1 in total at present
Thread-7 consumer consumption, currently 0

Recommended Today

The basic syntax and function of triggers in SQLSEVER

What is a trigger? Triggers are stored procedures that are executed automatically when a table is inserted, updated, or deleted. A special stored procedure that is automatically executed when a trigger inserts, updates, or deletes a table. Triggers are generally used for more complex check constraints. The difference between a trigger and a normal stored […]