一.ReentrantLock总结
1.一些方法:
ReentrantLock reentrantLock = new ReentrantLock();
1)加锁
reentrantLock.lock();
2)释放锁
reentrantLock.unlock();
3)尝试获取锁 获取不到返回false,获取不到直接放弃,不进入阻塞队列
reentrantLock.tryLock();
4)在给定时间内获取锁,获取不到就退出
reentrantLock.tryLock(2, TimeUnit.SECONDS);
5)锁绑定多个条件:一个 ReentrantLock 可以同时绑定多个 Condition 对象,更细粒度的唤醒线程,
通过reentrantLock.newCondition()创建一个条件变量condition
通过condition.await()方法,当前线程进入condition等待,释放锁;
通过condition.singal()方法,唤醒在condition中的线程;
6)reentrantLock.lockInterruptibly()`:获得可打断的锁
public static void main(String[] args) throws InterruptedException {
ReentrantLock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
try {
System.out.println("尝试获取锁");
lock.lockInterruptibly();
} catch (InterruptedException e) {
System.out.println("没有获取到锁,被打断,直接返回");
return;
}
try {
System.out.println("获取到锁");
} finally {
lock.unlock();
}
}, "t1");
lock.lock();
t1.start();
Thread.sleep(2000);
System.out.println("主线程进行打断锁");
t1.interrupt();
}