AbstractQueuedSynchronizer
ReentrantLock implements Lock 主要定义了一个内部类Sync是继承AbstractQueuedSynchronizer 所以看看:AbstractQueuedSynchronizer
定义了内部类Node 状态:CANCELLED(1),SIGNAL(-1),CONDITION(-2) /** Marker to indicate a node is waiting in shared mode / static final Node SHARED = new Node(); /* Marker to indicate a node is waiting in exclusive mode */ static final Node EXCLUSIVE = null; volatile int waitStatus; //默认是0,是什么状态? volatile Node prev; volatile Node next; volatile Thread thread; //其实是一个线程的双向链表的节点 Node nextWaiter; final boolean isShared() { return nextWaiter == SHARED; } Node() { // Used to establish initial head or SHARED marker }
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
AbstractQueuedSynchronizer 利用LockSupport,sun.misc.Unsafe,调用native方法进行信号量的操作。对维护的Thread双向链表进行信号量操作。 这里用到的park相当于wait,unpark相当于notify。
当前线程没有被设置等待状态。
park是捕获锁,相当于synchronized,wait是一种释放。
AbstractQueuedSynchronizer 就是提供了编程级别的wait/notify机制。 :D