1.ReentrantLock(可重入锁)
公平锁:新来的线程会进入等待队列,等待cpu调度,并不能保证线程一个接一个的执行
非公平锁:新来的线程会直接竞争锁
unlock方法在finally执行,保证释放锁
提供tryLock()方法,在一定尝试时间内获取锁,超过设定时间,放弃竞争
提供lockInterruptibly()方法,会对interrupt()方法做出响应。
使用CAS
2.构造条件 Condition
生产者:可以指定唤醒
消费者:可以指定唤醒
ReentrantLock lock = new ReentrantLock();
Condition p = lock.newCondition();
p.await();
p.singnalAll();
Condition c = lock.newCondition();
c.await();
c.singalAll();
condition创建了不同的等待队列。在唤醒线程的时候是唤醒指定队列的线程。
3.源码分析
- 公平锁
- trAcquire
final ``Thread current = Thread.``_currentThread_``()``;
int ``c = getState()``;
if ``(c == ``0``) {
``if ``(!hasQueuedPredecessors() &&``compareAndSetState(``0``, ``acquires)) {
- trAcquire
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;
- acquireQueued
- 非公平锁