【java】【12】AQS AbstractQueuedSynchronizer

1.原理

1.互斥變量標誌鎖對象的狀態
private volatile int state

2.雙向鏈表存儲等待的線程

3.沒有搶到鎖的線程阻塞,搶到鎖的線程執行
當搶到鎖的線程執行完後喚醒鏈表head指向的線程

阻塞和喚醒使用的是LockSupport類的park方法和unpark方法

2.兩個線程AThread、BThread搶佔鎖資源Demo

package com.yinzhen.demo.aqs;

import java.util.concurrent.locks.ReentrantLock;

public class DemoAQSThread extends Thread{
	
	//非公平鎖
	private static ReentrantLock reentrantLock = new ReentrantLock();
	

	public static void main(String[] args) {
		
		DemoAQSThread threadA = new DemoAQSThread();
		threadA.setName("ThreadA");
		threadA.start();
		
		DemoAQSThread threadB = new DemoAQSThread();
		threadB.setName("ThreadB");
		threadB.start();
		
	}

	@Override
	public void run() {
		
		try {
			reentrantLock.lock();
			
			long startTime = System.currentTimeMillis();
			System.out.println("hello---"+Thread.currentThread().getName());
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			System.out.println(Thread.currentThread().getName() 
					+"線程執行花費:"+(System.currentTimeMillis()-startTime));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			reentrantLock.unlock();
		}
		
	
	}

}

3.demo分析源碼

1.ThreadA和ThreadB同時執行reentrantLock.lock();

2.默認鎖資源的狀態state是0,ThreadA和ThreadB都使用CAS算法把0設置爲1,誰設置成功誰獲取到鎖

final void lock() {
    //默認鎖資源的狀態state是0,ThreadA和ThreadB都使用CAS算法把0設置爲1,誰設置成功誰獲取到鎖
	if (compareAndSetState(0, 1))
		setExclusiveOwnerThread(Thread.currentThread());
	else
		acquire(1);
}

3.假設ThreadA獲取了鎖,把自己設置成佔有鎖的線程
開始執行ThreadA的代碼

4.ThreadB沒有獲取到鎖資源

public final void acquire(int arg) {
	if (!tryAcquire(arg) &&
		acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
		selfInterrupt();
}

4.1嘗試獲取鎖,肯定是獲取不到的

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.2把自己放到阻塞隊列中

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 {
		    //把線程B節點前驅指向Head節點,線程B節點設置爲Tail節點
			node.prev = t;
			if (compareAndSetTail(t, node)) {
				t.next = node;
				return t;
			}
		}
	}
}

4.3把自己阻塞

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)) {
			    //如果node的前驅是head節點,並且獲取到了鎖
				setHead(node);
				p.next = null; // help GC
				failed = false;
				return interrupted;
			}
			//鎖獲取失敗
			if (shouldParkAfterFailedAcquire(p, node) &&
				parkAndCheckInterrupt())
				interrupted = true;
		}
	} finally {
		if (failed)
			cancelAcquire(node);
	}
}
//把自己的前驅的等待狀態設置爲SIGNAL
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;
}

//調用LockSupport.park(this)把自己阻塞
private final boolean parkAndCheckInterrupt() {
	LockSupport.park(this);
	return Thread.interrupted();
}

5.當線程A執行完後執行reentrantLock.unlock();方法喚醒head的下一個線程

public void unlock() {
	sync.release(1);
}

public final boolean release(int arg) {
	if (tryRelease(arg)) {
		Node h = head;
		if (h != null && h.waitStatus != 0)‘
		    //h.waitStatus != 0 表示後面又線程需要喚醒應該是-1狀態Node.SIGNAL
			// static final int SIGNAL    = -1;
		    //從頭節點開始喚醒下一個線程
			unparkSuccessor(h);
		return true;
	}
	return false;
}

/**
 * Wakes up node's successor, if one exists.
 *
 * @param node the node
 */
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);
}


protected final boolean tryRelease(int releases) {
	int c = getState() - releases;
	//狀態減releases
	if (Thread.currentThread() != getExclusiveOwnerThread())
		throw new IllegalMonitorStateException();
	boolean free = false;
	if (c == 0) {
	    //status爲0表示無鎖狀態
		free = true;
		//把佔有鎖的線程設置爲空
		setExclusiveOwnerThread(null);
	}
	setState(c);
	//釋放成功失敗
	return free;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章