BlockQueue

用法

Queue也就是队列,只能有两种基本的操作,在头部取走一个元素和在尾部增加一个元素,所以是一种FIFO结构(先进先出),不同于栈,栈是一种后进先出的数据结构。

阻塞Queue常用的方法:

  • add 增加一个元索 如果队列已满,则抛出一个IIIegaISlabEepeplian异常

  • remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常

  • element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常

  • offer 添加一个元素并返回true 如果队列已满,则返回false

  • poll 移除并返问队列头部的元素 如果队列为空,则返回null

  • peek 返回队列头部的元素 如果队列为空,则返回null

  • put 添加一个元素 如果队列满,则阻塞

  • take 移除并返回队列头部的元素 如果队列为空,则阻塞

    其中poll和take都是取走队列头部的元素,区别在于take是阻塞的,如果take的时候,队列为空,那么调用take方法的线程会一直阻塞知道队列元素不为空就会被唤醒,而poll不是阻塞的,poll方法只会检查此刻队列的状态,若为空则返回null。

    同理put和offer也是同一个道理。

应用

阻塞队列对应的是生产者消费者模型,在线程池中有所应用,线程池的内部就是一个阻塞队列,生产者往里面增加任务,而消费者也就是线程池中的线程就会不断地从阻塞队列中取出任务然后消费。

BlockQueue有两种一种是基于数组这种数据结构的ArrayBlockQueue,另外一种是基于链表LinkedBlockQueue。

源码

首先BlockQueue是线程安全的,其内部有一个ReentrantLock,由ReentrantLock产生两个Condition,其中一个Condition是调用take方法阻塞的线程集合,另外一个是调用put方法阻塞线程的集合,我们知道ReentrantLock是基于AQS,那么Condition就是对这些阻塞线程操作的封装,主要用于阻塞线程和唤醒在队列中等待线程。

take方法
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

首先lock加锁,然后循环检查队列中元素的个数,若为0则阻塞,若不为0,则返回一个元素并删除,dequeue的具体细节和用不同的数据结构实现是不一样的,BlcokQueue一般有基于数组数据结构实现,也有基于链表数据结构实现的。

其他的方法看了下都累死,都是检查状态,要不阻塞,要不执行成功。

一个对比

阻塞队列是线程安全的,那么我们和LinkedList来做一个对比,LinkedList不是线程安全的,程序就是几个不同的线程不断的在尾部增加1000个元素:

public class BlockQueueTest {

    private LinkedBlockingQueue<Integer> collection;

    private CountDownLatch countDownLatch;

    public BlockQueueTest(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
        collection = new LinkedBlockingQueue<Integer>();
    }

    private void addElement(final int ele) {
        for (int i = 0 ; i < 10; i ++) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000000; j ++)
                        collection.add(ele);

                    System.out.println(Thread.currentThread().getName() + " finish");
                    countDownLatch.countDown();
                }
            }.start();
        }
    }

    public LinkedBlockingQueue<Integer> getCollection() {
        return collection;
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        BlockQueueTest test = new BlockQueueTest(countDownLatch);
        test.addElement(10);
        countDownLatch.await();
        System.out.println(test.getCollection().size());
    }


}

运行结果是:

Thread-5 finish
Thread-4 finish
Thread-2 finish
Thread-3 finish
Thread-7 finish
Thread-6 finish
Thread-9 finish
Thread-0 finish
Thread-1 finish
Thread-8 finish
10000000

若使用LinkedList来测试:

public class BlockQueueTest {

    private LinkedList<Integer> collection;

    private CountDownLatch countDownLatch;

    public BlockQueueTest(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
        collection = new LinkedList<Integer>();
    }

    private void addElement(final int ele) {
        for (int i = 0 ; i < 10; i ++) {
            new Thread() {
                @Override
                public void run() {
                    for (int j = 0; j < 1000000; j ++)
                        collection.add(ele);

                    System.out.println(Thread.currentThread().getName() + " finish");
                    countDownLatch.countDown();
                }
            }.start();
        }
    }

    public LinkedList<Integer> getCollection() {
        return collection;
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
        BlockQueueTest test = new BlockQueueTest(countDownLatch);
        test.addElement(10);
        countDownLatch.await();
        System.out.println(test.getCollection().size());
    }


}

测试结果:

Thread-5 finish
Thread-4 finish
Thread-1 finish
Thread-2 finish
Thread-0 finish
Thread-6 finish
Thread-9 finish
Thread-3 finish
Thread-8 finish
Thread-7 finish
1294411

由于不是线程安全的,最终集合中的元素不是我们预期的10000000

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个比较复杂的问题,操作系统的实现涉及到很多知识,包括计算机组成原理、操作系统原理、数据结构与算法等等。下面是一个基于C语言模拟操作系统的框架,供您参考: ```c #include <stdio.h> #include <stdlib.h> // 定义进程控制块 typedef struct PCB { int pid; // 进程ID int state; // 进程状态:0-运行,1-就绪,2-阻塞 struct PCB *next; // 指向下一个进程控制块的指针 } PCB; // 定义进程队列 typedef struct Queue { PCB *front; // 队首指针 PCB *rear; // 队尾指针 int size; // 队列大小 } Queue; // 初始化队列 void initQueue(Queue *q) { q->front = q->rear = NULL; q->size = 0; } // 判断队列是否为空 int isEmpty(Queue *q) { return q->size == 0; } // 入队 void enQueue(Queue *q, PCB *pcb) { if (isEmpty(q)) { q->front = q->rear = pcb; } else { q->rear->next = pcb; q->rear = pcb; } q->size++; } // 出队 PCB* deQueue(Queue *q) { if (isEmpty(q)) { return NULL; } PCB *pcb = q->front; q->front = pcb->next; q->size--; return pcb; } // 创建进程 PCB* createProcess(int pid) { PCB *pcb = (PCB*)malloc(sizeof(PCB)); pcb->pid = pid; pcb->state = 1; pcb->next = NULL; return pcb; } // 销毁进程 void destroyProcess(PCB *pcb) { free(pcb); } int main() { Queue readyQueue; // 就绪队列 Queue blockQueue; // 阻塞队列 initQueue(&readyQueue); initQueue(&blockQueue); int pid = 0; // 进程ID计数器 while (1) { // 新建进程 if (rand() % 2 == 0) { PCB *pcb = createProcess(pid++); enQueue(&readyQueue, pcb); } // 运行进程 if (!isEmpty(&readyQueue)) { PCB *pcb = deQueue(&readyQueue); pcb->state = 0; printf("Running process %d...\n", pcb->pid); pcb->state = 1; enQueue(&readyQueue, pcb); } // 阻塞进程 if (!isEmpty(&readyQueue) && rand() % 3 == 0) { PCB *pcb = deQueue(&readyQueue); pcb->state = 2; printf("Blocking process %d...\n", pcb->pid); enQueue(&blockQueue, pcb); } // 唤醒进程 if (!isEmpty(&blockQueue) && rand() % 4 == 0) { PCB *pcb = deQueue(&blockQueue); pcb->state = 1; printf("Waking up process %d...\n", pcb->pid); enQueue(&readyQueue, pcb); } } return 0; } ``` 以上代码是一个简单的进程调度模拟程序,使用了队列来实现就绪队列和阻塞队列,每次循环会随机产生新进程、运行进程、阻塞进程和唤醒进程等操作。当然,这只是一个非常简单的模拟,真正的操作系统实现要比这要复杂得多。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值