面试系列 - 阻塞队列

阻塞队列

java中的阻塞队列在线程池中作为一个构造器的参数存在 BlockingQueue workQueue
阻塞队列的作用一般是用来存储已经submit但还没有执行完毕的线程。在多线程中,阻塞的意思是,在某些情况下会挂起线程,一旦条件成熟,被阻塞的线程就会被自动唤醒。阻塞队列就是用来存储线程池中的这些被挂起的线程的。

特点

先进先出

    /*进队列*/
    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();
        }
    }
    
	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();
        }
    }
    
	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;
    }

类型

有界队列
无界队列
直接提交队列
优先任务队列

线程池使用队列详情

四种线程池:
并发库中的blockingqueue(阻塞队列),主要提供了两个方法put()和take()
前者将对象放到队列中,如果队列已满,就等待有空闲。后者从head取一个对象,如果没有对象就等到有对象。

FixedThreadPool与SingleThreadPool都是采用的无界linkedblockingqueue实现。linkedblockingqueue中引入了两把锁takelock和putlock,显然分别用于take操作和put操作。入队出队用不同锁,可以同时进行入队出队操作。由于其实链表,查找较慢。

CacheThreadPool使用的时synchronousqueue队列,该队列是一种直接提交队列。

猜你喜欢

转载自blog.csdn.net/automal/article/details/107992522