在多线程开发中,会用到SynchronousQueue(new CachedThreadPool())和LinkedBlockingQueue(new FixedThreadPoll())

我们来简单分析一下这两个队列的区别

SynchronousQueue:

  offer():当线程offer操作时,当same mode时,加入队列失败,即时返回 (如果是put操作,元素会存储到队列中,并且阻塞等待);

当complimentary mode时,立即把元素transfer给等待的take线程

        take():线程take操作,当same mode时,该线程把元素存储到队列中,并且阻塞等待(如果是poll操作,元素会加入队列失败,即时返回);

当complimentary mode时,立即在队列中找到等待的put线程关联的元素,取出来,返回

 

LinkedBlockingQueue

  offer(): 线程把元素放入队列中(多线程并发竞争),返回,超过bound,返回失败

 1 /** Lock held by take, poll, etc */
 2     private final ReentrantLock takeLock = new ReentrantLock();
 3 
 4     /** Wait queue for waiting takes */
 5     private final Condition notEmpty = takeLock.newCondition();
 6 
 7     /** Lock held by put, offer, etc */
 8     private final ReentrantLock putLock = new ReentrantLock();
 9 
10     /** Wait queue for waiting puts */
11     private final Condition notFull = putLock.newCondition();
12 
13 
14 public boolean offer(E e) {
15         if (e == null) throw new NullPointerException();
16         final AtomicInteger count = this.count;
17         if (count.get() == capacity)
18             return false;
19         int c = -1;
20         Node<E> node = new Node<E>(e);
21         final ReentrantLock putLock = this.putLock;
22         putLock.lock();
23         try {
24             if (count.get() < capacity) {
25                 enqueue(node);
26                 c = count.getAndIncrement();
27                 if (c + 1 < capacity)
28                     notFull.signal();
29             }
30         } finally {
31             putLock.unlock();
32         }
33         if (c == 0)
34             signalNotEmpty();
35         return c >= 0;
36     }
offer方法

相关文章:

  • 2022-12-23
  • 2021-09-01
  • 2022-12-23
  • 2021-08-14
  • 2021-12-12
  • 2021-09-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-07-04
  • 2022-12-23
相关资源
相似解决方案