Java多线程系列--“JUC集合”10之 ConcurrentLinkedQueue(三)

2014-11-24 02:55:18 · 作者: · 浏览: 1
tNext(h);
}
说明:updateHead()的最终目的是更新表头为p,并设置h的下一个节点为h本身。
casHead(h,p)是通过CAS函数设置表头,若表头等于h的话,则设置表头为p。
lazySetNext()的源码如下:
void lazySetNext(Node val) {
UNSAFE.putOrderedObject(this, nextOffset, val);
}
putOrderedObject()函数,我们在前面一章“TODO”中介绍过。h.lazySetNext(h)的作用是通过CAS函数设置h的下一个节点为h自身,该设置可能会延迟执行。
情况2:如果表头的下一个节点为null,即链表只有一个“内容为null的表头节点”。
则调用updateHead(h, p),将表头更新p;然后返回null。
情况3:p=q
在“情况4”的发生后,会导致p=q;此时,“情况3”就会发生。当“情况3”发生后,它会跳转到restartFromHead标记重新操作。
情况4:其它情况。
设置p=q。
ConcurrentLinkedQueue示例
复制代码
1 import java.util.*;
2 import java.util.concurrent.*;
3
4 /*
5 * ConcurrentLinkedQueue是“线程安全”的队列,而LinkedList是非线程安全的。
6 *
7 * 下面是“多个线程同时操作并且遍历queue”的示例
8 * (01) 当queue是ConcurrentLinkedQueue对象时,程序能正常运行。
9 * (02) 当queue是LinkedList对象时,程序会产生ConcurrentModificationException异常。
10 *
11 * @author skywang
12 */
13 public class ConcurrentLinkedQueueDemo1 {
14
15 // TODO: queue是LinkedList对象时,程序会出错。
16 //private static Queue queue = new LinkedList();
17 private static Queue queue = new ConcurrentLinkedQueue();
18 public static void main(String[] args) {
19
20 // 同时启动两个线程对queue进行操作!
21 new MyThread("ta").start();
22 new MyThread("tb").start();
23 }
24
25 private static void printAll() {
26 String value;
27 Iterator iter = queue.iterator();
28 while(iter.hasNext()) {
29 value = (String)iter.next();
30 System.out.print(value+", ");
31 }
32 System.out.println();
33 }
34
35 private static class MyThread extends Thread {
36 MyThread(String name) {
37 super(name);
38 }
39 @Override
40 public void run() {
41 int i = 0;
42 while (i++ < 6) {
43 // “线程名” + "-" + "序号"
44 String val = Thread.currentThread().getName()+i;
45 queue.add(val);
46 // 通过“Iterator”遍历queue。
47 printAll();
48 }
49 }
50 }
51 }
复制代码
(某一次)运行结果:
复制代码
ta1, ta1, tb1, tb1,
ta1, ta1, tb1, tb1, ta2, ta2, tb2,
tb2,
ta1, ta1, tb1, tb1, ta2, ta2, tb2, tb2, ta3, tb3,
ta3, ta1, tb3, tb1, ta4,
ta2, ta1, tb2, tb1, ta3, ta2, tb3, tb2, ta4, ta3, tb4,
tb3, ta1, ta4, tb1, tb4, ta2, ta5,
tb2, ta1, ta3, tb1, tb3, ta2, ta4, tb2, tb4, ta3, ta5, tb3, tb5,
ta4, ta1, tb4, tb1, ta5, ta2, tb5, tb2, ta6,
ta3, ta1, tb3, tb1, ta4, ta2, tb4, tb2, ta5, ta3, tb5, tb3, ta6, ta4, tb6,
tb4, ta5, tb5, ta6, tb6,
复制代码
结果说明:如果将源码中的queue改成LinkedList对象时,程序会产生ConcurrentModificationException异常。