跟同步关键字有同样的内存语义。
与 synchronized 相比,ReentrantLock 更灵活。
// ************************** Synchronized **************************
// 1.用于代码块
synchronized (this) {}
// 2.用于对象
synchronized (object) {}
// 3.用于方法
public synchronized void test () {}
// 4.可重入
for (int i = 0; i < 100; i++) {
synchronized (this) {}
}
// ************************** ReentrantLock **************************
public void testLock() throw Exception {
// 1.初始化选择公平锁、非公平锁
ReentrantLock lock = new ReentrantLock(true);
// 2.可用于代码块
lock.lock();
try {
try {
// 3.支持多种加锁方式,比较灵活; 具有可重入特性
if(lock.tryLock(100, TimeUnit.MILLISECONDS)){ }
} finally {
// 4.手动释放锁
lock.unlock()
}
} finally {
lock.unlock();
}
}
方法 | 描述 |
lock | 获取锁的方法,若锁被其他线程获取,则等待(阻塞) |
lockinterruptibly | 在锁的获取过程中可以中断当前线程 |
tryLock |
尝试非阻塞地获取锁,立即返回 |
unlock | 释放锁 |
Tips:
根据Lock接口的源码注释,Lock接口的实现, 具备和同步关键字同样的内存语义。
可重入
public class ReentrantDemo1 {
private static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
lock.lock(); // block until condition holds
try {
System.out.println("第一次获取锁");
System.out.println("当前线程获取锁的次数" + lock.getHoldCount());
lock.lock();
System.out.println("第二次获取锁了");
System.out.println("当前线程获取锁的次数" + lock.getHoldCount());
} finally {
lock.unlock();
lock.unlock();
}
System.out.println("当前线程获取锁的次数" + lock.getHoldCount());
// 如果不释放,此时其他线程是拿不到锁的
new Thread(() -> {
System.out.println(Thread.currentThread() + " 期望抢到锁");
lock.lock();
System.out.println(Thread.currentThread() + " 线程拿到了锁");
}).start();
}
}
可响应中断
中断只是标记线程应该被中断,但不是马上停止
- lockInterruptibly 可在等待的过程响应中断
// 可响应中断
public class LockInterruptiblyDemo1 {
private Lock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
LockInterruptiblyDemo1 demo1 = new LockInterruptiblyDemo1();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
demo1.test(Thread.currentThread());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
Thread.sleep(500); // 等待0.5秒,让thread1先执行
thread2.start();
Thread.sleep(2000); // 两秒后,中断thread2
thread2.interrupt();
}
public void test(Thread thread) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + ", 想获取锁");
lock.lockInterruptibly(); //注意,如果需要正确中断等待锁的线程,必须将获取锁放在外面,然后将InterruptedException抛出
try {
System.out.println(thread.getName() + "得到了锁");
Thread.sleep(10000); // 抢到锁,10秒不释放
} finally {
System.out.println(Thread.currentThread().getName() + "执行finally");
lock.unlock();
System.out.println(thread.getName() + "释放了锁");
}
}
}
lockInterruptibly()/lock() 区别
// 缓存示例
public class CacheDataDemo {
// 创建一个map用于缓存
private Map map = new HashMap<>();
private static ReadWriteLock rwl = new ReentrantReadWriteLock();
public static void main(String[] args) {
// 1 读取缓存里面的数据
// cache.query()
// 2 如果换成没数据,则取数据库里面查询 database.query()
// 3 查询完成之后,数据塞到塞到缓存里面 cache.put(data)
}
public Object get(String id) {
Object value = null;
// 首先开启读锁,从缓存中去取(防止数据不一致,要释放了读锁才会加写锁)
rwl.readLock().lock();
try {
value = map.get(id);
if (value == null) {
// TODO database.query(); 全部查询数据库 ,缓存雪崩
// 必须释放读锁,否则无法加写锁
rwl.readLock().unlock();
// 如果缓存中没有释放读锁,上写锁。防止多个相同的查询请求同时查询数据库
rwl.writeLock().lock(); // 所有线程在此处等待 1000 1 999 (在同步代码里面再次检查是否缓存)
try {
value = map.get(id);
// 双重检查。如果已经写了缓存,则其他线程直接获取
if (mvalue == null) {
// TODO value = ...如果缓存没有,就去数据库里面读取
}
// 写锁降级读锁,保证了之前读取操作的数据一致性。(在释放读锁前,其他线程无法修改缓存的值)
rwl.readLock().lock();
} finally {
rwl.writeLock().unlock(); // 释放写锁@
}
}
/* 在这里又进行了一系列操作,在操作过程中,有可能数据改变导致缓存内容改变
此时,要在写锁中加入读锁,防止类似于 幻读,脏读 等的产生
*/
} finally {
rwl.readLock().unlock();
}
return value;
}
}
可以更细粒度的的控制等待,与 ReentrantLock 配合使用
JDK 中队列的实现
// condition 实现队列线程安全。
public class QueueDemo {
final Lock lock = new ReentrantLock();
// 指定条件的等待 - 等待有空位
final Condition notFull = lock.newCondition();
// 指定条件的等待 - 等待不为空
final Condition notEmpty = lock.newCondition();
// 定义数组存储数据
final Object[] items = new Object[100];
int putptr, takeptr, count;
// 写入数据的线程,写入进来
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length) // 数据写满了
notFull.await(); // 写入数据的线程,进入阻塞
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal(); // 唤醒指定的读取线程
} finally {
lock.unlock();
}
}
// 读取数据的线程,调用take
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await(); // 线程阻塞在这里,等待被唤醒
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal(); // 通知写入数据的线程,告诉他们取走了数据,继续写入
return x;
} finally {
lock.unlock();
}
}
}
public class ThreadSafeMap extends HashMap {
//使用读写锁保证线程安全
private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
private ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
private ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
@Override
public V get(Object key) {
V value;
try {
readLock.lock();
return super.get(key);
} finally {
readLock.unlock();
}
}
@Override
public V put(K key, V value) {
V ret;
try {
writeLock.lock();
return super.put(key, value);
} finally {
writeLock.unlock();
}
}
}
/**
* 自己手动实现的一个 reentrantLock
*
*/
public class GzyLock implements Lock {
//需要 CAS 自旋的方式去实现
//模仿 monitor obj 的重量级锁 有一个 owner
private static AtomicReference owner = new AtomicReference<>();
private static LinkedBlockingDeque waiters = new LinkedBlockingDeque<>();
@Override
public void lock() {
boolean addQueue = true;
while (!tryLock()){
//第一次进来会放到queue
if(addQueue) {
//如果没有获取到锁,就先存到 queue
waiters.offer(Thread.currentThread());
addQueue = false;
}else {
//park 等待被唤醒。这里不能用 wait/notify 因为需要在同步代码块用
LockSupport.park();
}
//唤醒后尝试争抢,没抢到继续等
}
//抢到锁,移除掉
waiters.remove(Thread.currentThread());
}
@Override
public boolean tryLock() {
//适用当前线程尝试加锁
return owner.compareAndSet(null, Thread.currentThread());
}
@Override
public void unlock() {
//unlock 的时候,要唤醒等待线程
//如果释放锁成功了,才会唤起
//这里用 if 是因为,一定不会出现 循环
if (owner.compareAndSet(Thread.currentThread(), null)) {
//一次唤醒所有在等待队列的
for (Thread waiter : waiters) {
//唤起等待队列的线程
LockSupport.unpark(waiter);
}
}
}
public static void main(String[] args) throws InterruptedException {
Adder adder = new Adder();
for (int j = 0; j < 10; j++) {
Thread addThread = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
adder.add();
}
});
addThread.start();;
}
Thread.sleep(1000L);
System.out.println(adder.i);
}
static class Adder{
Lock lock = new GzyLock();
int i = 0;
public void add(){
lock.lock();
try {
i++;
}finally {
lock.unlock();
}
}
}
}