@@ -112,7 +112,7 @@ public final boolean compareAndSet(long expect, long update) {
112
112
113
113
### 出队列
114
114
![ cdl] ( https://i.imgur.com/G5Irgel.jpg )
115
- * poll()
115
+ * poll() 出队列不会阻塞,如果队列为空则返回null。
116
116
``` Java
117
117
public E poll() {
118
118
restartFromHead:
@@ -142,4 +142,75 @@ public final boolean compareAndSet(long expect, long update) {
142
142
}
143
143
}
144
144
}
145
+ ```
146
+
147
+ ### 其他方法
148
+ * size() 检查队列大小,O(n),为了保证并发性不得不每次都遍历链表。
149
+ ``` Java
150
+ public int size() { // 返回检查队列的大小
151
+ int count = 0 ;
152
+ for (Node<E > p = first(); p != null ; p = succ(p))
153
+ if (p. item != null )
154
+ // Collection.size() spec says to max out
155
+ if (++ count == Integer . MAX_VALUE )
156
+ break ;
157
+ return count;
158
+ }
159
+ ```
160
+
161
+ * isEmpty() 判断链表非空,O(1)级别
162
+
163
+ ### Test
164
+ * 生产者
165
+ ``` Java
166
+ public class ConcurrentLinkQueueProducer implements Runnable {
167
+ private ConcurrentLinkedQueue<Integer > q;
168
+ public ConcurrentLinkQueueProducer (ConcurrentLinkedQueue<Integer > q ) {
169
+ super ();
170
+ this . q = q;
171
+ }
172
+ @Override
173
+ public void run () {
174
+ AtomicInteger al = new AtomicInteger (0 );// 通过AtomicInteger保证原子性,避免锁。
175
+ while (true ){
176
+ q. offer(al. get());
177
+ System . out. println(" Producer: put " + al. getAndIncrement() + " into queue..." );
178
+ try {
179
+ Thread . sleep(10 );
180
+ } catch (InterruptedException e) {
181
+ e. printStackTrace();
182
+ }
183
+ }
184
+ }
185
+ }
186
+ ```
187
+
188
+ * 消费者
189
+ ``` Java
190
+ public class ConcurrentLinkedQueueConsumer implements Runnable {
191
+ private ConcurrentLinkedQueue<Integer > q;
192
+ public ConcurrentLinkedQueueConsumer (ConcurrentLinkedQueue<Integer > q ) {
193
+ super ();
194
+ this . q = q;
195
+ }
196
+ @Override
197
+ public void run () {
198
+ try {
199
+ while (true ){
200
+ System . out. println(" Consumer: get " + q. poll() + " from queue..." );
201
+ Thread . sleep(10 );
202
+ }
203
+ } catch (InterruptedException e) {
204
+ e. printStackTrace();
205
+ }
206
+ }
207
+
208
+ public static void main (String [] args ) throws InterruptedException {
209
+ ConcurrentLinkedQueue<Integer > q = new ConcurrentLinkedQueue<> ();
210
+ Thread producer = new Thread (new ConcurrentLinkQueueProducer (q));
211
+ producer. start();
212
+ producer. join(100 );
213
+ new Thread (new ConcurrentLinkedQueueConsumer (q)). start();
214
+ }
215
+ }
145
216
```
0 commit comments