1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | /** * @author 五月的仓颉http://www.cnblogs.com/xrq730/p/7056614.html */ public class AbstractQueuedSynchronizerTest { @Test public void testAbstractQueuedSynchronizer() { Lock lock = new ReentrantLock(); Runnable runnable0 = new ReentrantLockThread(lock); Thread thread0 = new Thread(runnable0); thread0.setName("线程0"); Runnable runnable1 = new ReentrantLockThread(lock); Thread thread1 = new Thread(runnable1); thread1.setName("线程1"); Runnable runnable2 = new ReentrantLockThread(lock); Thread thread2 = new Thread(runnable2); thread2.setName("线程2"); thread0.start(); thread1.start(); thread2.start(); for (;;); } private class ReentrantLockThread implements Runnable { private Lock lock; public ReentrantLockThread(Lock lock) { this.lock = lock; } @Override public void run() { try { lock.lock(); for (;;); } finally { lock.unlock(); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // Try the fast path of enq; backup to full enq on failure Node prev = tail; if (prev != null) { node.prev = prev; if (compareAndSetTail(prev, node)) { prev.next = node; return node; } } enq(node); return node; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private Node enq(final Node node) { for (;;) { Node t = tail; if (t == null) { // Must initialize if (compareAndSetHead(new Node())) tail = head; } else { node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |