一.简介
jdk中独占锁的实现除了使用关键字synchronized外,还可以使用ReentrantLock。虽然在性能上ReentrantLock和synchronized没有什么区别,但ReentrantLock相比synchronized而言功能更加丰富,使用起来更为灵活,也更适合复杂的并发场景。
二.使用
ReentrantLock类实现了Lock接口,重写了下面这几个方法,后面通过逐个讲述每个方法的使用,来介绍ReentrantLock类的使用。
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
Condition newCondition();
1.简单示例
先给出一个最基础的使用案例,也就是实现锁的功能。
public class ReentrantLockTest {
private static Lock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new ThreadDemo(lock), "线程A");
Thread thread2 = new Thread(new ThreadDemo(lock), "线程B");
thread1.start();
thread2.start();
}
}
class ThreadDemo implements Runnable {
private Lock lock;
public ThreadDemo(Lock lock) {
this.lock = lock;
}
@Override
public void run() {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "获取了锁");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "释放了锁");
lock.unlock();
}
}
}
上面一段代码实现了最简单的功能,即独占锁,输出如下:
线程A获取了锁
线程A释放了锁
线程B获取了锁
线程B释放了锁
2.公平锁实现
ReentrantLock和synchronized不一样的地方,就是可以实现公平锁。公平锁是指当锁可用时,在锁上等待时间最长的线程将获得锁的使用权。而非公平锁则随机分配这种使用权。在创建ReentrantLock的时候通过传进参数true创建公平锁,如果传入的是false或没传参数则创建的是非公平锁。
ReentrantLock lock = new ReentrantLock(true);
下面演示一下公平锁的实现:
public class ReentrantLockTest {
private static Lock lock = new ReentrantLock(true);
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new ThreadDemo(lock), "线程A");
Thread thread2 = new Thread(new ThreadDemo(lock), "线程B");
Thread thread3 = new Thread(new ThreadDemo(lock), "线程C");
Thread thread4 = new Thread(new ThreadDemo(lock), "线程D");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
class ThreadDemo implements Runnable {
private Lock lock;
public ThreadDemo(Lock lock) {
this.lock = lock;
}
@Override
public void run() {
for (int i = 0; i < 2; i++) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "获取了锁");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
我们开启4个线程,让每个线程都获取释放锁两次,可以看到线程几乎是轮流的获取到了锁,输出如下:
线程A获取了锁
线程B获取了锁
线程C获取了锁
线程D获取了锁
线程A获取了锁
线程B获取了锁
线程C获取了锁
线程D获取了锁
3.非公平锁实现
和synchronized一样,默认的ReentrantLock实现是非公平锁,因为相比公平锁,非公平锁性能更好。直接看一下非公平锁的实现结果:
线程A获取了锁
线程A获取了锁
线程B获取了锁
线程B获取了锁
线程C获取了锁
线程C获取了锁
线程D获取了锁
线程D获取了锁
可以看到,线程会重复获取锁。如果申请获取锁的线程足够多,那么可能会造成某些线程长时间得不到锁。这就是非公平锁的“饥饿”问题。
4.可响应中断
当使用synchronized实现锁时,阻塞在锁上的线程除非获得锁否则将一直等待下去,也就是说这种无限等待获取锁的行为无法被中断。而ReentrantLock给我们提供了一个可以响应中断的获取锁的方法lockInterruptibly()。 即当通过lockInterruptibly()方法去获取锁时,如果线程正在等待获取锁,则这个线程能够响应中断,即中断线程的等待状态。该方法可以用来解决死锁问题。下面举一个响应中断的例子。
public class ReentrantLockTest {
private static Lock lock1 = new ReentrantLock();
private static Lock lock2 = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new ThreadDemo(lock1, lock2), "线程A");
Thread thread2 = new Thread(new ThreadDemo(lock2, lock1), "线程B");
thread1.start();
thread2.start();
thread1.interrupt();
}
}
class ThreadDemo implements Runnable {
private Lock firstLock;
private Lock secondLock;
public ThreadDemo(Lock firstLock, Lock secondLock) {
this.firstLock = firstLock;
this.secondLock = secondLock;
}
@Override
public void run() {
try {
firstLock.lockInterruptibly();
Thread.sleep(100);
secondLock.lockInterruptibly();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
firstLock.unlock();
secondLock.unlock();
System.out.println(Thread.currentThread().getName() + "正常结束");
}
}
}
输出如下:
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at multithread.ThreadDemo.run(ReentrantLockTest.java:60)
at java.lang.Thread.run(Thread.java:748)
Exception in thread "线程A" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:151)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1261)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
at multithread.ThreadDemo.run(ReentrantLockTest.java:66)
at java.lang.Thread.run(Thread.java:748)
线程B正常结束
在上述代码中,我们定义了两个锁lock1和lock2,然后使用两个线程构造死锁场景。如果没有外界中断,该程序将处于死锁状态永远无法停止。我们通过使其中一个线程中断,来结束线程间毫无意义的等待。被中断的线程将抛出异常,而另一个线程将能在获取锁后正常结束。
5.限时等待
ReentrantLock还给我们提供了获取锁限时等待的方法tryLock()和tryLock(long time, TimeUnit unit)。
tryLock()方法是有返回值的,它表示用来尝试获取锁,如果获取成功,则返回true,如果获取失败(即锁已被其他线程获取),则返回false,tryLock()方法会立即返回获取锁的结果。
tryLock(long time, TimeUnit unit)方法和tryLock()方法是类似的,只不过区别在于这个方法在拿不到锁时会等待一定的时间,在时间期限之内如果还拿不到锁,就返回false。如果如果一开始拿到锁或者在等待期间内拿到了锁,则返回true。
下面举一个获取锁限时等待的例子:
public class ReentrantLockTest {
private static Lock lock1 = new ReentrantLock();
private static Lock lock2 = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new ThreadDemo(lock1, lock2), "线程A");
Thread thread2 = new Thread(new ThreadDemo(lock2, lock1), "线程B");
thread1.start();
thread2.start();
}
}
class ThreadDemo implements Runnable {
private Lock firstLock;
private Lock secondLock;
public ThreadDemo(Lock firstLock, Lock secondLock) {
this.firstLock = firstLock;
this.secondLock = secondLock;
}
@Override
public void run() {
try {
while (true) {
if (!firstLock.tryLock()) {
Thread.sleep(100);
continue;
}
Thread.sleep(100);
if (!secondLock.tryLock()) {
System.out.println(Thread.currentThread().getName() + "释放了锁");
firstLock.unlock();
Thread.sleep(100);
} else {
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
firstLock.unlock();
secondLock.unlock();
System.out.println(Thread.currentThread().getName() + "正常结束");
}
}
}
上述代码通过tryLock()方法和失败重试机制解决了死锁问题,输出如下:
线程A释放了锁
线程B正常结束
线程A正常结束
6.等待通知机制
使用synchronized结合Object上的wait和notify方法可以实现线程间的等待通知机制。ReentrantLock结合Condition接口同样可以实现这个功能。而且相比前者使用起来更清晰也更简单。
Condition由ReentrantLock对象创建,并且可以同时创建多个。
Condition notEmpty = lock.newCondition();
Condition notFull = lock.newCondition();
Condition接口在使用前必须先调用ReentrantLock的lock()方法获得锁。之后调用Condition接口的await()将释放锁,并且在该Condition上等待,直到有其他线程调用该Condition的signal()方法唤醒线程。使用方式和wait,notify类似。
下面通过一段代码示范使用Condition实现简单的阻塞队列。
public class ConditionTest {
public static void main(String[] args) {
MyBlockingQueue<Integer> queue = new MyBlockingQueue<>(2);
for (int i = 0; i < 10; i++) {a
int data = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
queue.enqueue(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Integer data = queue.dequeue();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
class MyBlockingQueue<E>{
int size; //阻塞队列最大容量
Lock lock = new ReentrantLock();
LinkedList<E> list = new LinkedList<>();
Condition notFull = lock.newCondition(); //队列满时的等待条件
Condition notEmpty = lock.newCondition(); //队列空时的等待条件
public MyBlockingQueue(int size){
this.size = size;
}
public void enqueue(E e) throws InterruptedException {
lock.lock();
try{
while (list.size() == size){ //队列已满,在notFull条件上等待
notFull.await();
}
list.add(e);
System.out.println("入队:" + e);
notEmpty.signal(); //通知在notEmpty条件上等待的线程
} finally {
lock.unlock();
}
}
public E dequeue() throws InterruptedException {
E e;
lock.lock();
try{
while (list.size() == 0){ //队列为空,在notEmpty条件上等待
notEmpty.await();
}
e = list.removeFirst();
System.out.println("出队:" + e);
notFull.signal(); //通知在notFull条件上等待的线程
return e;
} finally {
lock.unlock();
}
}
}
输出如下:
入队:0
入队:1
出队:0
入队:2
出队:1
入队:3
出队:2
入队:4
出队:3
入队:5
出队:4
入队:6
出队:5
入队:7
出队:6
入队:8
出队:7
入队:9
出队:8
出队:9
网友评论