Java 生产者消费者及手撕源码 (jdk阻塞队列写法)

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

public class Main2 {


    public static void main(String[] args) {
        ArrayBlockingQueue<Milke> arrayBlockingQueue = new ArrayBlockingQueue<Milke>(100);
        for (int i = 0; i < 10; i++) {
            new Thread(new Producer(arrayBlockingQueue), i + "号生产者").start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(new Consumer(arrayBlockingQueue), i + "消费者").start();
        }
    }


}
class Milke {}
class Consumer implements Runnable{
    private ArrayBlockingQueue<Milke> queue;
    public Consumer(ArrayBlockingQueue<Milke> queue){this.queue = queue;}
    @Override
    public void run() {
        while (true) {
            consume();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void consume() {
        try{
            queue.take();
            System.out.println(Thread.currentThread().getName() + " : 消费了一个元素,queue剩余:" + queue.size());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Producer implements Runnable{
    private ArrayBlockingQueue<Milke> queue;
    public Producer(ArrayBlockingQueue<Milke> queue){this.queue = queue;}
    @Override
    public void run() {
        while(true) {
            produce();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void produce() {
        try{
            queue.put(new Milke());
            System.out.println(Thread.currentThread().getName() + " : 放入了一个元素,queue剩余:" + queue.size());

        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
 

写法:
1 主类里面有一个阻塞队列,消费者,生产者也有一个私有阻塞队列,通过构造器传参把主类的队列让消费者和生产者得到
2 消费者c 生产者p,c 、p都实现runnable接口重写run方法,run方法写死循环,c里面调c的私有消费方法,p里面调p的私有生产方法
3 消费者 直接调blockingQueue的take ,记得trycatch,生产者直接调blockingQueue的put,打印剩余元素个数
4 主类里面用thread 构造器传入c p 对象,并传入线程名称,循环启动,记得先new 生产者再new消费者

原理:
源码:

    /**
     * Inserts the specified element at the tail of this queue, waiting
     * for space to become available if the queue is full.
     *
     * @throws InterruptedException {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
    /**
     * Inserts element at current put position, advances, and signals.
     * Call only when holding lock.
     */
    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
        /**
     * Extracts element at current take position, advances, and signals.
     * Call only when holding lock.
     */
    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

  • 1 阻塞对列:ArrayBlockingQueue 的插入和取出对应有相应的并发安全的方法:take(消费) put(取出)
    • 前提原理:两个condition un_empty 和 un_full un_empty (消费者线程用的condition)不锁的时候消费者线程可以消费反正阻塞的时候不能消费,un_full(生产者用的condition)不锁的时候生产者可以生产,反之阻塞的时候不能生产。
    • take的时候如果有值就会取,取完唤醒”un_full“的condition(暗示producer队列现在有空缺了(不满),可以放了),如果没有值就会阻塞”un_empty“的condition(暗示consumer线程现在没值可取了,等等再来拿吧),put的时候满了就阻塞un_full,(暗示producer线程别放了,等等吧),put的时候如果队列没满,还可以放就会加元素,同时唤醒”un_empty“(暗示消费者线程可以消费了)
      画个图:
      Java 生产者消费者及手撕源码 (jdk阻塞队列写法)_第1张图片

你可能感兴趣的:(java,面试)