Java中关于AbstractQueuedSynchronizer的入门(二)

AQS是一个同步器的基础类,里面的关键字段:

    //如下关键字段都是volatile类型

    /**
* Head of the wait queue, lazily initialized. Except for
* initialization, it is modified only via method setHead. Note:
* If head exists, its waitStatus is guaranteed not to be
* CANCELLED.
*/
private transient volatile Node head; //获取锁的链式队列的头 /**
* Tail of the wait queue, lazily initialized. Modified only via
* method enq to add new wait node.
*/
private transient volatile Node tail;//获取锁的链式队列的尾 /**
* The synchronization state.
*/
private volatile int state; //记录所的状态

通过如下示例代码进行跟踪查看队列实际细节:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class AQS {
public static void main(String[] args) throws Exception { final Lock lock = new ReentrantLock(); lock.lock();
lock.lock();
newThread(lock,"lock-1").start();
Thread.sleep(500);
newThread(lock,"lock-2").start();
Thread.sleep(500);
newThread(lock,"lock-3").start();
Thread.sleep(500);
     //断点处,可以在此处进行跟踪
lock.lock(); Thread.sleep(5000000);
lock.unlock();
lock.unlock();
lock.unlock(); } public static Thread newThread(final Lock lock,final String threadName ) {
return new Thread(new Runnable() { @Override
public void run() {
System.out.println(threadName+"正在获取锁!");
lock.lock();
}
},threadName); } }

注意类的继承细节:

abstract static class Sync extends AbstractQueuedSynchronizer 
static final class NonfairSync extends Sync 

此时细节:

Java中关于AbstractQueuedSynchronizer的入门(二)

Java中关于AbstractQueuedSynchronizer的入门(二)

三个线程lock-1,lock-2,lock-3正在队列中等待获取锁。

接下来查看一下lock-1如何存储到等待队列中的:

上一篇:java + spring (jython\python\script) Error:SyntaxError: no viable alternative at character '\n'


下一篇:Window.onload事件