Java 并发编程详解:Lock 接口及其实现 ReentrantLock
在 Java 并发编程中,锁机制是确保多线程环境下数据一致性和安全性的关键。Java 提供了 Lock 接口及其实现类 ReentrantLock,相比于传统的 synchronized 关键字,提供了更多的控制和灵活性。本文将详细介绍 Lock 接口及其实现 ReentrantLock,包括其特性、使用方法和实际应用示例。
一、Lock 接口
Lock 接口是 Java 并发包中定义的一个接口,用于实现锁的机制。与 synchronized 相比,Lock 接口提供了更多的锁控制方式和更加灵活的操作。
1. 主要方法
- void lock(): 获取锁。如果锁已经被另一个线程持有,则当前线程会被阻塞,直到获得锁。
- void lockInterruptibly() throws InterruptedException: 获取锁,但在等待时可以响应中断。
- boolean tryLock(): 尝试获取锁。如果成功获取到锁,返回 true,否则返回 false。不会阻塞线程。
- boolean tryLock(long time, TimeUnit unit) throws InterruptedException: 在指定的时间内尝试获取锁。
- void unlock(): 释放锁。
- Condition newCondition(): 返回一个绑定到此 Lock 实例的新 Condition 实例,用于实现等待/通知机制。
二、ReentrantLock 类
ReentrantLock 是 Lock 接口的一个具体实现类,是一个可重入锁。可重入锁的特点是,持有锁的线程可以多次获取该锁而不会被阻塞。
1. 特性
- 可重入性: 持有锁的线程可以再次获取该锁,不会被阻塞。
- 公平锁和非公平锁: ReentrantLock 支持公平锁和非公平锁。公平锁按照线程请求的顺序分配锁,而非公平锁则无序分配,可能会使某些线程长期得不到锁。
- Condition 支持: 提供 Condition 对象,实现线程间的协调,类似于 Object 类中的 wait、notify 和 notifyAll 方法。
2. 构造方法
- ReentrantLock(): 创建一个默认的非公平锁。
- ReentrantLock(boolean fair): 创建一个公平或非公平锁,取决于参数 fair 的值。
三、ReentrantLock 的使用
1. 基本使用
使用 ReentrantLock 进行锁操作,通常需要配合 try-finally 语句,确保锁在不再需要时被释放。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private final Lock lock = new ReentrantLock();
private int counter = 0;
public void increment() {
lock.lock(); // 获取锁
try {
counter++;
} finally {
lock.unlock(); // 确保在最后释放锁
}
}
public int getCounter() {
lock.lock();
try {
return counter;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLockExample example = new ReentrantLockExample();
// 创建多个线程来测试 ReentrantLock
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
};
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Counter: " + example.getCounter());
}
}
2. 使用 Condition 实现生产者-消费者模型
ReentrantLock 提供的 Condition 可以更灵活地实现线程间的协调,类似于传统的 wait 和 notify。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerConsumerExample {
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private final int[] buffer = new int[10];
private int count, putptr, takeptr;
public void put(int value) throws InterruptedException {
lock.lock();
try {
while (count == buffer.length) { // 缓冲区已满
notFull.await();
}
buffer[putptr] = value;
if (++putptr == buffer.length) putptr = 0;
count++;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public int take() throws InterruptedException {
lock.lock();
try {
while (count == 0) { // 缓冲区为空
notEmpty.await();
}
int value = buffer[takeptr];
if (++takeptr == buffer.length) takeptr = 0;
count--;
notFull.signal();
return value;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ProducerConsumerExample example = new ProducerConsumerExample();
Runnable producer = () -> {
for (int i = 0; i < 100; i++) {
try {
example.put(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable consumer = () -> {
for (int i = 0; i < 100; i++) {
try {
int value = example.take();
System.out.println("Consumed: " + value);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
try {
producerThread.join();
consumerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
四、总结
Lock
接口 提供了比 synchronized 关键字更灵活和丰富的锁机制。ReentrantLock
是 Lock 接口的一个实现,支持可重入、可选择的公平锁以及提供 Condition 对象来实现复杂的线程间协调。- 使用 ReentrantLock 可以提高多线程环境下程序的并发性能和可控性,适用于需要复杂锁控制的场景。
通过合理使用 Lock 接口及其实现 ReentrantLock,可以更有效地管理并发,确保线程安全,提高程序的可靠性和性能。