AQS-预备-FIFOMutex

阅读更多

通过AtomicBoolean 和队列实现一个线程FIFO的Lock工具,

一步步接近AQS!!!

 

package com.horizon.thread.aqs;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

public class FIFOMutex {
	private final AtomicBoolean locked = new AtomicBoolean(false);
	/**
	 * 线程先进先出队列
	 */
	private final Queue waiters = new ConcurrentLinkedQueue();

	public void lock() {
		boolean wasInterrupted = false;
		Thread current = Thread.currentThread();
		//把当前线程加入队列
		waiters.add(current);

		// Block while not first in queue or cannot acquire lock
		//如果当前线程不是第一个:不是第一个肯定,肯定有其他线程在持有资源(保证公平性)
		//即使是第一个:加锁失败,即使是第一个线程,如果上一个线程没有释放锁 ,那么也应该进入等待
		while (waiters.peek() != current || !locked.compareAndSet(false, true)) {
			LockSupport.park(this);
			if (Thread.interrupted()) // ignore interrupts while waiting
				wasInterrupted = true;
		}

		//可以把第一个线程移除了,因为已经占用了资源
		waiters.remove();
		if (wasInterrupted) // reassert interrupt status on exit
			current.interrupt();
	}

	public void unlock() {
		//释放锁,其他的线程 此时也不能占用资源
		locked.set(false);
		
		//此时线程才可以真正执行
		LockSupport.unpark(waiters.peek());
	}

}

 

你可能感兴趣的:(AQS-预备-FIFOMutex)