3.21 ReentrantLock
相对于synchronized它具备如下特点:
- 可中断
- 可设置超时时间
- 可以设置为公平锁
- 支持多个条件变量
与synchronized一样,都支持可重入
基本语法
//获取值
reentrantLock.lock();
try {
//临界区
} finally {
//释放锁
reentrantLock.unLock();
}
1、可重入
可重入是指同一个线程如果首次获得了这把锁,那么因为它是这把锁的拥有者,因此有权利再次获取这把锁
如果是不可重入锁,那么第二次获得锁时,自己也会被锁挡住。
package com.sharing_model.reentrant_lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*可重入锁: 可重入
*/
public class ReentrantLockTest {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
lock.lock();
try {
System.out.println("enter main");
m1();
} finally {
lock.unlock();
}
}
public static void m1() {
lock.lock();
try {
System.out.println("enter m1");
m2();
} finally {
lock.unlock();
}
}
public static void m2() {
lock.lock();
try {
System.out.println("enter m2");
} finally {
lock.unlock();
}
}
}
2、可打断
package com.sharing_model.reentrant_lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*可重入锁: 可打断
*/
public class ReentrantLockTest2 {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
//如果没有竞争,那么此方法就会获取lock对象锁
//如果有竞争就进入阻塞队列,可以被其它线程用interrupt方法打断
System.out.println("尝试获得锁");
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("没有获得锁");
return;
}
try {
System.out.println("获取到锁");
} finally {
lock.unlock();
}
}, "t1");
//主线程先获得锁,t1线程阻塞
lock.lock();
t1.start();
//3秒后,打断t1线程
Thread.sleep(3*1000);
t1.interrupt();
}
}
注释掉3秒后,打断t1线程,添加如下所示代码
//5秒后,主线程释放锁,t1线程获得锁
Thread.sleep(5*1000);
lock.unlock();
3、锁超时
package com.sharing_model.reentrant_lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*可重入锁: 锁超时
*/
public class ReentrantLockTest3 {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println("尝试获得锁");
if (!lock.tryLock()) {
System.out.println("获取不到锁");
return;
}
try {
System.out.println("获得到锁");
} finally {
lock.unlock();
}
}, "t1");
//主线程先获得锁
lock.lock();
t1.start();
}
}
4、解决哲学家就餐问题
package com.sharing_model.reentrant_lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 通过ReentrantLock解决哲学家就餐问题
*/
public class ResolvePhilosopherProblem {
public static void main(String[] args) {
Chopstick1 c1 = new Chopstick1("1");
Chopstick1 c2 = new Chopstick1("2");
Chopstick1 c3 = new Chopstick1("3");
Chopstick1 c4 = new Chopstick1("4");
Chopstick1 c5 = new Chopstick1("5");
new Philosopher("苏格拉底", c1, c2).start();
new Philosopher("柏拉图", c2, c3).start();
new Philosopher("亚里士多德", c3, c4).start();
new Philosopher("赫拉克利特", c4, c5).start();
new Philosopher("阿基米德", c5, c1).start();
}
}
class Philosopher extends Thread {
String name;
Chopstick1 left;
Chopstick1 right;
public Philosopher(String name, Chopstick1 left, Chopstick1 right) {
this.name = name;
this.left = left;
this.right = right;
}
@Override
public void run() {
while (true) {
//尝试获得左手筷子
if (left.tryLock()) {
try {
if (right.tryLock()) {
try {
eat();
} finally {
right.unlock();
}
}
} finally {
left.unlock();
}
}
}
}
private void eat() {
System.out.println(name + "eating...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Chopstick1 extends ReentrantLock {
public Chopstick1(String s) {
}
}
5、公平锁
https://www.bilibili.com/video/BV16J411h7Rd?p=125
公平锁就是,当有线程获得锁之后,如果后面再有线程想要获得锁,陷入阻塞状态,当占用锁的线程释放锁之后,先阻塞的线程先获得锁。
公平锁一般是没有必要的。会降低并发度。
6、条件变量
synchronized中也有条件变量,就是我们讲原理时哪个waitSet休息室,当条件不满足时,进入waitSet中等待,ReentrantLock的条件变量比Synchronized强大之处在于,他是支持多个条件变量的,这就好比
- sysnchronized是那些不满足条件的线程都在一间休息室等消息
- 而ReentrantLock支持多件休息室,有专门等烟的休息室、专门等早餐的休息室、唤醒也是按照休息室来唤醒
使用流程:
- await前需要获得锁
- await执行后,会释放锁,进入conditionObject等待
- awiat的线程被唤醒(或打断、或超时)取重新竞争lock锁
- 竞争lock锁成功之后,从await后继续执行
package com.sharing_model.reentrant_lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 条件变量
* 和Synchronized中的waitSet很像
*/
public class ConditionVar {
static final Object room = new Object();
static boolean hasCigarette = false;
static boolean hasTakeout = false;
static ReentrantLock ROOM = new ReentrantLock();
//等待烟的休息室
static Condition waitCigaretteSet = ROOM.newCondition();
//等外卖的休息室
static Condition waitTakeoutSet = ROOM.newCondition();
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
ROOM.lock();
try {
System.out.println("小南:有烟没?" + hasCigarette);
while (!hasCigarette) {
System.out.println("小南:没有,先歇会!");
try {
waitCigaretteSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("小南:有烟没?" + hasCigarette);
if (hasCigarette) {
System.out.println("小南:可以开始干活了");
} else {
System.out.println("小南:没干成活。。。");
}
} finally {
ROOM.unlock();
}
}, "小南").start();
new Thread(() -> {
ROOM.lock();
try {
System.out.println("小女:外卖送到了没?" + hasTakeout);
while (!hasTakeout) {
System.out.println("小女:没外卖。先歇会!");
try {
waitTakeoutSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("小女:外卖送到没?" + hasTakeout);
if (hasTakeout) {
System.out.println("小女:可以开始干活了");
} else {
System.out.println("小女:没干成活");
}
} finally {
ROOM.unlock();
}
},"小女").start();
Thread.sleep(1000);
//送外卖线程
new Thread(() -> {
ROOM.lock();
try {
hasTakeout = true;
waitTakeoutSet.signal();
} finally {
ROOM.unlock();
}
},"送外卖的").start();
//送烟的线程
new Thread(() -> {
ROOM.lock();
try {
hasCigarette = true;
waitCigaretteSet.signal();
} finally {
ROOM.unlock();
}
},"送烟的").start();
}
}