文章目录
- 使用 synchronized 的场景
- 使用 ReentrantLock 的场景
- 综合考虑
使用 synchronized 的场景
synchronized 是 Java 内置的同步机制,使用起来比较简单且常用于如下场景:
1、简单的同步逻辑
:当你的同步逻辑非常简单,比如只需要对某个方法或代码块进行互斥访问时,synchronized 非常适用,因为它的语法简洁且易于维护。
java">public synchronized void simpleMethod() {// critical section
}
2、隐式监视器锁
:synchronized 隐式地使用对象的监视器锁来控制同步,不需要显式的锁定和解锁操作,因此避免了锁忘记释放的问题。
3、异常安全
:synchronized 块在异常发生时,会自动释放锁,确保不会因为未释放锁而导致死锁问题。
使用 ReentrantLock 的场景
ReentrantLock 是 java.util.concurrent.locks 包中提供的,更高级的锁机制,适用于以下场景:
1、需要更灵活的锁控制
:ReentrantLock 提供了更多的锁控制功能,如 tryLock()
(尝试锁定)和 lockInterruptibly
()(可中断锁定),使得能够响应中断或超时。
java">import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class TryLockExample {private final Lock lock = new ReentrantLock();public void tryMethod() {if (lock.tryLock()) {try {// critical section} finally {lock.unlock();}} else {// handle the case where lock was not acquired}}
}
2、需要公平锁机制
:ReentrantLock 支持公平锁(即先请求先获得锁),这在某些需要防止线程饥饿的场景中特别有用。
java">Lock fairLock = new ReentrantLock(true); // true for fairness
3、需要条件变量
:ReentrantLock 提供了条件变量(Condition
),可以更精细地控制线程等待和通知机制,适用于需要多个条件队列的复杂同步场景。
java">import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;// 假设我们有一个界面程序,其中一个生产者线程和两个消费者线程,
// 并且我们希望消费者1只处理奇数编号的任务,而消费者2只处理偶数编号的任务。
public class MultiConditionExample {private static final Lock lock = new ReentrantLock();private static final Condition conditionOdd = lock.newCondition();private static final Condition conditionEven = lock.newCondition();private static int count = 0;public static void main(String[] args) {Thread producer = new Thread(new Producer());Thread consumer1 = new Thread(new ConsumerOdd(), "Consumer-Odd");Thread consumer2 = new Thread(new ConsumerEven(), "Consumer-Even");producer.start();consumer1.start();consumer2.start();}static class Producer implements Runnable {@Overridepublic void run() {while (true) {try {lock.lock();count++;System.out.println("Produced: " + count);if (count % 2 == 0) {conditionEven.signal(); // Signal consumers waiting on even condition} else {conditionOdd.signal(); // Signal consumers waiting on odd condition}} finally {lock.unlock();}try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}static class ConsumerOdd implements Runnable {@Overridepublic void run() {while (true) {try {lock.lock();while (count % 2 == 0) {conditionOdd.await(); // Wait for odd number condition}// Process odd numberSystem.out.println(Thread.currentThread().getName() + " consumed: " + count);} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally {lock.unlock();}}}}static class ConsumerEven implements Runnable {@Overridepublic void run() {while (true) {try {lock.lock();while (count % 2 != 0) {conditionEven.await(); // Wait for even number condition}// Process even numberSystem.out.println(Thread.currentThread().getName() + " consumed: " + count);} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally {lock.unlock();}}}}
}
java">class MultiConditionExampleWithWaitNotify {private static final Object lock = new Object();private static int count = 0;public static void main(String[] args) {Thread producer = new Thread(new Producer());Thread consumerOdd = new Thread(new ConsumerOdd(), "Consumer-Odd");Thread consumerEven = new Thread(new ConsumerEven(), "Consumer-Even");producer.start();consumerOdd.start();consumerEven.start();}static class Producer implements Runnable {@Overridepublic void run() {while (true) {synchronized (lock) {count++;System.out.println("Produced: " + count);if (count % 2 == 0) {lock.notifyAll(); // Notify consumers waiting on even condition} else {lock.notifyAll(); // Notify consumers waiting on odd condition}}try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}static class ConsumerOdd implements Runnable {@Overridepublic void run() {while (true) {synchronized (lock) {try {while (count % 2 == 0) {lock.wait(); // Wait for odd number condition}// Process odd numberSystem.out.println(Thread.currentThread().getName() + " consumed: " + count);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}}static class ConsumerEven implements Runnable {@Overridepublic void run() {while (true) {synchronized (lock) {try {while (count % 2 != 0) {lock.wait(); // Wait for even number condition}// Process even numberSystem.out.println(Thread.currentThread().getName() + " consumed: " + count);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}}
}
wait 和 notify:只能使用单一的监视器锁,并通过 notify 或 notifyAll 来通知等待线程。由于所有线程都在同一个锁对象上等待,即使只需要唤醒部分线程(例如只唤醒等待奇数的线程),也必须通知所有等待的线程(使用 notifyAll),这样会导致非目标线程频繁被唤醒和再次等待。
Condition:可以创建多个 Condition 实例,在不同的条件队列上管理等待和通知。只会唤醒指定条件下的线程,从而提高效率。
综合考虑
简洁性和安全性:如果你的同步需求简单
,且不需要复杂的锁定逻辑,选择 synchronized 更为简洁和安全。
灵活性和功能:如果需要更灵活的锁控制
、更高的性能、更多的特性(如条件变量、尝试锁定、响应中断等),ReentrantLock 提供更强大的功能。