【操作系统】阻塞队列的实现及底层分析

  1. 阻塞队列
/**
 * 自定义阻塞队列
 * 生产-消费者模式
 * 一个生产者,一个消费者
 */
public class MyArrayBlockingQueue {
    //存储元素的数组
    private long[] array;
    //永远指向队列的第一个元素的索引位置
    private int frontIndex;
    //永远在队列的最后一个位置的下一个位置
    private int rearIndex;
    //队列元素的个数
    private int size;

    public MyArrayBlockingQueue(int capacity){
        array =new long[capacity];
        frontIndex=0;
        rearIndex=0;
        size=0;
    }
    /**
     * 入队操作
     * @param e
     * @throws InterruptedException
     */
    public synchronized void put(long e) throws InterruptedException {
        //先判断数组是否已满,避免假唤醒的情况,使用while
        while (array.length==size){
            //TODO:
            this.wait();
        }

        //预期队列一定不是满的
        array[rearIndex]=e;
        rearIndex++;
        //数组越界
        if (rearIndex ==array.length){
            rearIndex=0;
        }
        size++;
        //若有线程阻塞,一定是消费者等待
        notifyAll();
    }

    /**
     * 出队操作
     * @return
     * @throws InterruptedException
     */
    public synchronized long take() throws InterruptedException {
        while (size==0){
            //队列为空
            wait();
        }
        long e=array[frontIndex];
        frontIndex++;
        if (frontIndex==array.length){
            frontIndex=0;
        }
        size--;
        //若有线程阻塞,一定是生产者等待
        notifyAll();
        return e;
    }
}

  1. 测试
package JavaSE.线程.blockQueue;

import java.util.Scanner;

public class Test {
    static MyArrayBlockingQueue queue =new MyArrayBlockingQueue(3);

    static class MyThread extends Thread {
        @Override
        public void run() {
            Scanner sc =new Scanner(System.in);
            long e=sc.nextLong();

            //将元素入队
            try {
                queue.put(e);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread thread =new MyThread();
        thread.start();

        //队列为空,主线程会阻塞,等待生产者生产
        long e=queue.take();
        System.out.println(e);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值