ReentrantLock
ReentrantLock是可重入的独占锁实际上还是通过同步抽象队列实现的。它里面就是维护的一个state状态值。在默认的情况下,state的值为0,表示当前锁没有被任何线程占有。当一个线程第一次获取该锁的时候,会尝试使用CAS来设置state的值为1,如果CAS成功,那么当前线程就获取该锁,然后记录该锁的持有者为当前线程。在该线程没有释放锁的情况下尝试第二次获取,状态值会被设置为2,就是可重入的次数。在该线程释放锁的时候,会尝试使用CAS让状态值减一,如果减一之后状态值为0,则当前线程释放该锁。
我们看一下lock函数
final void lock() {
//CAS设置状态值
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
//调用AQS的acquire方法
else
acquire(1);
}
我们可以知道如果CAS失败会执行acquice方法
public final void acquire(int arg) {
//如果tryAcquire失败,那么会将线程放入阻塞队列
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
ReentrantLock内部有两种锁,一种是非公平锁(默认),另一种是公平锁。首先看非公平锁的tryAcquire方法
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//如果为0,锁空闲状态
if (c == 0) {
if (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;
}
公平锁其实实现差不多,只是添加了公平的策略。
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//如果为0,锁空闲状态
if (c == 0) {
//添加公平策略
if (!hasQueuedPredecessors() &&
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;
}
我们看一下另一个获取锁的方法
trylock()
尝试获取锁,如果该锁没有线程持有,那么当前线程就会获取锁,并返回true,否则返回false。注意,这个方法不会引起线程的阻塞
释放锁unlock()方法
尝试释放锁,如果当前线程持有该锁,调用这个方法会让AQS里面的状态值减一。如果减一之后状态值为0,那么当前线程就会释放这个锁,否则就是仅仅减一而已。
Condition
它的作用于wait和notify相同,wait与notify是和同步锁一起使用的,Condition是和重入锁一起使用的。通过Lock接口的newCondition可以一个与当前重入锁绑定的Condition实例。
await():方法会使该线程等待,同时释放锁,当其他线程使用signal方法的时候,线程会重新获得锁并继续执行。
singal():会唤醒一个正在等待的线程,singalAll会唤醒所有等待的线程。
下面通过一个简单的示例说明这两者之间的关系
package thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class TestReentrantLock {
static ReentrantLock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
try {
//获得所
lock.lock();
System.out.println(System.currentTimeMillis()+" "+Thread.currentThread().getName());
//使这个线程释放锁,
condition.await();
System.out.println(System.currentTimeMillis()+" "+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//最终释放锁
lock.unlock();
}
}
},"thread1").start();
Thread.sleep(1000);
try {
lock.lock();
//唤醒正在等待的线程
condition.signalAll();
System.out.println(System.currentTimeMillis()+" "+Thread.currentThread().getName());
Thread.sleep(1000);
}finally {
lock.unlock();
}
new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lock();
System.out.println(System.currentTimeMillis()+" "+Thread.currentThread().getName());
}finally {
lock.unlock();
}
}
},"thread2").start();
}
}
执行结果如下
1569127763162 thread1
1569127764177 main
1569127765191 thread1
1569127765222 thread2
分析:
thread1首先获得锁,然后输出,这时候thread1释放锁,thread1进入等待被唤醒状态,然后main线程获得锁,输出,并唤醒thread1,并释放锁。接着由于thread1被唤醒,那么他会重新获得锁,并执行完毕,最后释放锁。最后就是thread2获得锁并释放锁的过程。