简体   繁体   English

Java阻塞队列实现问题

[英]Java Blocking Queue Implementation Questions

The common implementation is here , Java's built-in implementation is here . 常见的实现在这里 ,Java的内置实现在这里 I have two questions regarding these two implementations: 关于这两个实现,我有两个问题:

1) The first implementation use synchronized key word on put() and take() methods, which means only one thread can access one method. 1)第一个实现在put()和take()方法上使用了synchronized关键字,这意味着只有一个线程可以访问一个方法。 Let's say if thread A call put() and found the queue is full, so it's waiting, then no one can ever call take() method since the lock is not released yet, how can the implementation be used? 假设如果线程A调用put()并发现队列已满,因此正在等待,则由于锁尚未释放,因此没有人可以调用take()方法,该实现如何使用?

2) Java's built-in uses two locks: takeLock and putLock, and used in put() and take() respectively. 2)Java的内置函数使用两个锁:takeLock和putLock,分别用于put()和take()。 I saw that the interval queue is a linked list, which is not thread-safe, how can that be done? 我看到间隔队列是一个链表,它不是线程安全的,怎么办?

As already mentioned in some of the comments the first implementation just uses traditional wait()/notify() mechanism where one thread waits (and of course releasing lock) for being notified by other threads. 正如一些评论中已经提到的那样,第一个实现仅使用传统的wait()/ notify()机制,其中一个线程等待(当然释放锁)供其他线程通知。

The second one uses different locks each for put and take operations. 第二个使用不同的锁进行放置和取出操作。 So the individual operations (simultaneous put() or take()) are synchronous. 因此,各个操作(同时put()或take())是同步的。 But they need to communicate with each other when queue is full or empty. 但是当队列已满或为空时,它们需要彼此通信。 So they interact with each other through condition . 因此,它们通过condition彼此交互。 Checkout the two private methods- 签出两种私人方法-

    /**
     * Signals a waiting take. Called only from put/offer (which do not
     * otherwise ordinarily lock takeLock.)
     */
    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
    }

    /**
     * Signals a waiting put. Called only from take/poll.
     */
    private void signalNotFull() {
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            notFull.signal();
        } finally {
            putLock.unlock();
        }
    }

put method signals other threads trying to take/poll from empty queue and take method signals other threads trying to put elements into full queue. put方法向尝试从空队列中进行/轮询的其他线程发出信号,而take方法向试图将元素放入完整队列的其他线程发出信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM