一. 公平锁
1. 定义:
公平锁的官方文档:
Threads acquire a fair lock in the order in which they requested it
公平锁:
就是很公平,在并发环境中,每个线程在获取锁时,
会先查看此锁维护的等待队列,如果为空,
或者当前线程就是等待队列的第一个,就占有锁,
否则就会加入到等待队列中,
以后会按照FIFO的规则从队列中取到自己。
简单来说:就是按照顺序办事,不可以加塞,插队等。
2. 实现:
Lock lock = new ReentrantLock(true);
ReentrantLock默认是非公平锁,加上参数true就可以变成公平锁。
加参数 Lock lock = new ReentrantLock(true);
看底层源码是公平锁
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
二. 非公平锁
1. 定义:
非公平锁的官方文档:a nonfair lock permits barging: threads requesting a lock
can jump ahead of the queue of waiting threads if the lock happens
to be available when it is requested.
非公平锁比较粗鲁,上来就直接尝试占有资源,
如果尝试失败,就再采用类似公平锁那种方式。
简单来说:就是他不想按规矩办事,喜欢加塞,插队,
如果失败了,则老老实实的排队。
2. 实现:
Lock lock = new ReentrantLock();
默认不加参数 Lock lock = new ReentrantLock();
看底层源码是非公平锁
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/
public ReentrantLock() {
sync = new NonfairSync();
}
Synchronized而言,是一种非公平锁