Lock锁实现生产者和消费者,分析AQS加锁和解锁源码
Lock锁实现生产者和消费者
仓库
public class WareHouse {
//产品个数
private int num;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void producer(){
try {
lock.lock();
while (num == 10){
condition.await();
}
num++;
System.out.println(Thread.currentThread().getName()+"--->"+num);
condition.signal();
}catch (Exception e){
System.out.println(e);
}finally {
lock.unlock();
}
}
public void consumer(){
try {
lock.lock();
while (num == 0){
condition.await();
}
System.out.println(Thread.currentThread().getName()+"--->"+num);
num--;
condition.signal();
}catch (Exception e){
System.out.println(e);
}finally {
lock.unlock();
}
}
}
生产者
public class Producer implements Runnable{
private WareHouse wareHouse;
public Producer(WareHouse wareHouse){
this.wareHouse = wareHouse;
}
@Override
public void run() {
while (true){
wareHouse.producer();
}
}
}
消费者
public class Consumer implements Runnable {
private WareHouse wareHouse;
public Consumer(WareHouse wareHouse){
this.wareHouse = wareHouse;
}
@Override
public void run() {
while (true){
wareHouse.consumer();
}
}
}
测试
public class TestConsumerAndProducer {
public static void main(String[] args) {
WareHouse wareHouse = new WareHouse();
Producer producer = new Producer(wareHouse);
Consumer consumer = new Consumer(wareHouse);
Thread t1 = new Thread(producer);
t1.setName("生产产品");
Thread t2 = new Thread(consumer);
t2.setName("消费产品");
t1.start();
t2.start();
}
}
AQS源码简单分析
AQS
中 维护了一个volatile int state
(代表共享资源)和一个FIFO
线程等待队列(多线程争用资源被阻塞时会进入此队列)。
这里volatile
能够保证多线程下的可见性,当state=1
则代表当前对象锁已经被占有,其他线程来加锁时则会失败,加锁失败的线程会被放入一个FIFO
的等待队列中,比列会被UNSAFE.park()
操作挂起,等待其他获取锁的线程释放锁才能够被唤醒。
另外state
的操作都是通过CAS
来保证其并发修改的安全性。
ReentrantLock类
ReentrantLock类的内部有一个抽象的静态内部类Sync,继承了AbstractQueuedSynchronizer,
然后内部又有公平锁和非公平锁继承Sync类,默认是使用非公平锁。
首先了解保存线程的节点node
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;
}
waitStatus是节点Node定义的,它是标识线程的等待状态,它主要有如下四个值:
- CANCELLED = 1:线程已被取消;
- SIGNAL = -1:当前线程的后继线程需要被unpark(唤醒);
- CONDITION = -2 :线程(处在Condition休眠状态)在等待Condition唤醒;
- PROPAGATE = –3:(共享锁)其它线程获取到“共享锁”.
假设此时有A B C三个线程
**1:
**执行过程,
当有A B C三个线程调用lock()方法竞争锁时,若A线程获得锁,会使用乐观锁把state状态设置为1,并把A线程设置为当前锁的拥有者,当B线程加锁时,则失败。
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
**2:
**然后调用acquire()方法。
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
**3:
**它里面会调用tryAcquire()
方法,去尝试获得锁,
- 如果state状态为0,则改变state为1,成功返回true,
- 如果state不为0,则判断当前线程是否是锁的拥有者,如果是,
则state+1,返回true,这就实现了重入锁,否则都不满足返回false。
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
**4:
**然后执行addWaiter()
方法,把当前线程放到一个node节点里,加入到FIFO先进先出队列中。如果当前队列为null,则执行enq()方法创建一个队列。
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 pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
----------------------------------------------------------------------------
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;
}
}
}
}
5:
然后执行acquireQueued()
方法,里面主要有一个无限循环。
- 获得当前线程节点node的前一个节点,
判断这个前节点是否为head头节点,即FIFO队列中的头节点。还要执行tryAcquire()
方法(源码在步骤3
)尝试获得锁,如果都返回true,则把当前线程节点设置为head节点,原来头节点的next置为null,进行垃圾回收。如果为false,则向下执行。 - shouldParkAfterFailedAcquire()方法会去判断它是否应该被阻塞,如果为true,则执行parkAndCheckInterrupt()方法,进行线程中断。
LockSupport.park()
把线程挂起。(LockSupport.unpark()
唤醒挂起的线程)
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();//获得当前节点的前一个节点
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
假设线程C和线程B操作一样,此FIFO队列中,有两个线程B、C等待。
6:
此时A线程执行完,执行unlock()方法—>release()—>tryRelease()
释放锁成功,会把state置为0,把当前锁的拥有者(setExclusiveOwnerThread())
置为null。
public void unlock() {
sync.release(1);
}
---------------------------------------------------------------------------------------public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
-------------------------------------------------------------------------------------------
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
7:
在步骤5
中的shouldParkAfterFailedAcquire()
会把线程节点的waitStatus置为Node.SIGNAL (SIGNAL =-1)
,所以会执行unparkSuccessor()方法,此时的node为头结点head,
- 首先把node节点的waitStatus置为0。
- 取出节点s,在FIFO(先进先出)队列中,
此时节点s为线程B
,然后执行LockSupport.unpark(),唤醒线程B,即唤醒步骤5
被挂起的线程。
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;
if (s == null || s.waitStatus > 0) {
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);
}