您的位置:首页 > 编程语言 > Java开发

java并发库 Lock 公平锁和非公平锁

2016-03-28 10:08 471 查看
jdk1.5并发包中ReentrantLock的创建可以指定构造函数的boolean类型来得到公平锁或非公平锁,关于两者区别,java并发编程实践里面有解释

公平锁: Threads acquire a fair lock in the order in which they requested it

非公平锁: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.

公平锁,就是很公平,在并发环境中,每个线程在获取锁时会先查看此锁维护的等待队列,如果为空,或者当前线程线程是等待队列的第一个,就占有锁,否则就会加入到等待队列中,以后会按照FIFO的规则从队列中取到自己

非公平锁比较粗鲁,上来就直接尝试占有锁,如果尝试失败,就再采用类似公平锁那种方式

//公平获取锁  java.util.concurrent.locks.ReentrantLock$FairSync.java


protected
final
boolean
tryAcquire(
int
acquires)
{
 
final
Thread
current = Thread.currentThread();
 
int
c
= getState();
 
//状态为0,说明当前没有线程占有锁
 
if
(c
==
0
) {
//如果当前线程是等待队列的第一个或者等待队列为空,则通过cas指令设置state为1,当前线程获得锁
 
if
(isFirst(current)
&&
 
compareAndSetState(
0
,
acquires)) {
 
setExclusiveOwnerThread(current);
 
return
true
;
 
}
 
}
//如果当前线程本身就持有锁,那么叠加状态值,持续获得锁
 
else
if
(current
== getExclusiveOwnerThread()) {
 
int
nextc
= c + acquires;
 
if
(nextc
<
0
)
 
throw
new
Error(
"Maximum
lock count exceeded"
);
 
setState(nextc);
 
return
true
;
 
}
 
//以上条件都不满足,那么线程进入等待队列。
 
return
false
;
}


//非公平获取锁  java.util.concurrent.locks.ReentrantLock$UnFairSync.java


final boolean nonfairTryAcquire(int acquires) {

final Thread current = Thread.currentThread();

int c = getState();

if (c == 0) {

//如果当前没有线程占有锁,当前线程直接通过cas指令占有锁,管他等待队列,就算自己排在队尾也是这样

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: