Multithreading - producer-consumer model the three ways

  Producer-consumer model to solve the problem of strong coupling between the two by a blocking queue. Blocking queue processing power equivalent to a buffer, the balance of consumers and producers.

  Blocking queue data - producers do not produce, not blocking queue data - consumers do not consume

一、synchronized+wait+notifyAll

 produce

Package com.ProductCusromer.method2; 

Import java.util.List;
 Import java.util.Random; 

/ ** 
 * @author Millet 
 * @date 2020/3/30 17:59 
 * / 
public  class Product2 is the implements the Runnable {
     Private List List ; 

    public Product2 is (List List) {
         the this .list = List; 
    } 
    // plurality of producers corresponding to a plurality of consumers 
    @Override
     public  void RUN () { 
        the Random Random = new new the Random (50); // equivalent goods 
        while( To true ) {
             the synchronized (List) {
                 the while (list.size ()> 0 ) {
                     // set the data write is stopped, waiting for consumer spending finish 
                    the try { 
                        list.wait (); 
                    } the catch (InterruptedException E) { 
                        e.printStackTrace (); 
                    } 
                } 
                the try { 
                    the Thread.sleep ( 1000 ); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace (); 
                } 
                //This shows that the implementation of the data collection is not the 
                list.add ((random.nextInt (50 )));
                 // prompt 
                System.out.println (Thread.currentThread () getName () + " thread produced:" + list.. GET (0 )); 
                list.notifyAll (); 
            } 
        } 
    } 
}

 consumer

package com.ProductCusromer.method2;

import java.util.List;

/**
 * @author Millet
 * @date 2020/3/30 18:07
 */
public class Consumer2 implements Runnable {
    private List list;

    public Consumer2(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while(true){
            synchronized (list){
                while(list.size()<=0){//适合多生产者多消费者
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                 try {
                     Thread.sleep(500);
                  } catch (InterruptedException e) {
                       e.printStackTrace();
                   }

                 //提示
                  System.err.println(Thread.currentThread().getName()+"线程消费了:"+ list.remove(0));
                  list.notifyAll();
                }
            }
    }
}

 

二, ReetrantLock + Condition

Producers

package com.ProductCusromer.method3;

import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author Millet
 * @date 2020/3/30 17:59
 */
public class Product3 implements Runnable {
    private List list;
    private Lock mLock;
    private Condition mCondition;
    public Product3(List list, Lock lock, Condition condition) {
        this.list = list;
        the this .mLock = Lock;
         the this .mCondition = for condition Condition; 
    } 
    // a producer corresponding to a consumer 
    @Override
     public  void RUN () { 
        the Random Random = new new the Random (50); // equivalent goods 
        the while ( to true ) { 
            mlock .lock (); 
            IF (list.size ()> 0 ) {
                 // set the data write is stopped, waiting for consumer spending Ends 
                the try { 
                    mCondition.await (); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace ();
                } 
            } 
            The try { 
                the Thread.sleep ( 1000 ); 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 
            } 
            // perform a set of instructions that no data 
            List.add ((random.nextInt (50 )));
             / / prompt 
            System.out.println (Thread.currentThread () getName () + " thread produced:." List.get + (0 )); 
            mCondition.signalAll (); 
            mLock.unlock (); 
        } 
    } 
}

 

 consumer

package com.ProductCusromer.method2;

import java.util.List;

/**
 * @author Millet
 * @date 2020/3/30 18:07
 */
public class Consumer2 implements Runnable {
    private List list;

    public Consumer2(List list) {
        this.list = list;
    }

    @Override
    public void run() {
        while(true){
            synchronized (list){
                while(list.size()<=0){//适合多生产者多消费者
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                 try {
                     Thread.sleep(500);
                  } catch (InterruptedException e) {
                       e.printStackTrace();
                   }

                 //提示
                  System.err.println(Thread.currentThread().getName()+"线程消费了:"+ list.remove(0));
                  list.notifyAll();
                }
            }
    }
}

 

Three, BlockingQueue achieve

Producers

 

package com.ProductCusromer.method3;

import java.util.concurrent.BlockingQueue;

/**
 * @author Millet
 * @date 2020/3/30 21:28
 */
public class Product4 implements Runnable {
    private BlockingQueue queue;
    private String name;
    public Product4(String name, BlockingQueue queue) {
        this.queue = queue;
        this.name = name;
    }
    @Override
    public void run() {
        while(true) {
             The try {
                 int Val = ( int ) Math.random (); 
                queue.put (Val); 
                System.out.println (name + "Production:". "Current queue length:" + Val + + queue.size () ); 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 
            } 
        } 
    } 
}

 

consumer

package com.ProductCusromer.method3;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author Millet
 * @date 2020/3/30 21:28
 */
public class Consumer4 implements Runnable{
    private BlockingQueue queue;
    private String name;
    public Consumer4(String name, BlockingQueue queue) {
        this.queue = queue;
        this.name = name;
    }
    @Override
    public void run() {
        try {
            while (true){
                int val = (int) queue.take();
                System.out.println(name + "消费:"+val+".当前队列长度:"+ queue.size());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

test

package com.ProductCusromer.method3;

import com.ProductCusromer.method1.Consumer1;
import com.ProductCusromer.method1.Product1;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Millet
 * @date 2020/3/30 20:33
 */
public class Main {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(20);
        Product4 producer1 = new Product4("生产1号", queue);
        Product4 producer2 = new Product4("生产2号", queue);
        Product4 producer3 = new Product4("生产3号", queue);

        Consumer4 consumer1 = newConsumer4 ( "Consumer No. 1" , Queue); 
        Consumer4 consumer2 = new new Consumer4 ( "Consumer No. 2" , Queue); 

// start producer thread production of 
        new new the Thread (producerl) .start ();
         new new the Thread (Producer2) .start ();
         new new the thread (producer3) .start (); 

// start consumer thread consumption. 
        new new the Thread (consumer1) .start ();
         new new the Thread (consumer2) .start (); 
    } 
}

 

result

 

Guess you like

Origin www.cnblogs.com/qmillet/p/12601518.html