当前位置: 首页 > news >正文

什么时候用synchronized,什么时候用Reentrantlock

文章目录

  • 使用 synchronized 的场景
  • 使用 ReentrantLock 的场景
  • 综合考虑

使用 synchronized 的场景

synchronized 是 Java 内置的同步机制,使用起来比较简单且常用于如下场景:

1、简单的同步逻辑:当你的同步逻辑非常简单,比如只需要对某个方法或代码块进行互斥访问时,synchronized 非常适用,因为它的语法简洁且易于维护。

public synchronized void simpleMethod() {// critical section
}

2、隐式监视器锁:synchronized 隐式地使用对象的监视器锁来控制同步,不需要显式的锁定和解锁操作,因此避免了锁忘记释放的问题。

3、异常安全:synchronized 块在异常发生时,会自动释放锁,确保不会因为未释放锁而导致死锁问题。

使用 ReentrantLock 的场景

ReentrantLock 是 java.util.concurrent.locks 包中提供的,更高级的锁机制,适用于以下场景:

1、需要更灵活的锁控制:ReentrantLock 提供了更多的锁控制功能,如 tryLock()(尝试锁定)和 lockInterruptibly()(可中断锁定),使得能够响应中断或超时。

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 支持公平锁(即先请求先获得锁),这在某些需要防止线程饥饿的场景中特别有用。

Lock fairLock = new ReentrantLock(true); // true for fairness

3、需要条件变量:ReentrantLock 提供了条件变量(Condition),可以更精细地控制线程等待和通知机制,适用于需要多个条件队列的复杂同步场景。

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();}}}}
}
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 提供更强大的功能。

http://www.lryc.cn/news/444727.html

相关文章:

  • [ffmpeg]音频格式转换
  • SSRF工具类-SsrfTool
  • python集合运算介绍及示例代码
  • 『功能项目』按钮的打开关闭功能【73】
  • Linux 常用命令 - more 【分页显示文件内容】
  • Kotlin Android 环境搭建
  • 常见协议及其默认使用的端口号
  • 04-Docker常用命令
  • 数字化转型中的供应链管理优化
  • 【Python报错已解决】SyntaxError: invalid syntax
  • 树上差分+lca 黑暗的锁链
  • opencv4.5.5 GPU版本编译
  • 线性跟踪微分器TD详细测试(Simulink 算法框图+SCL完整源代码)
  • LabVIEW闪退
  • 【WPF】03 动态生成控件
  • 调试LTE模块碰到的4字节对齐问题
  • 一篇讲完HTML核心内容
  • 2024icpc(Ⅱ)网络赛补题 G
  • AIGC时代!AI的“iPhone时刻”与投资机遇
  • Kubernetes调度单位Pod
  • C语言指针篇
  • Unity 使用Editor工具查找 Prefab 中的指定脚本
  • Frida-JSAPI:Interceptor使用
  • 【深度学习】(3)--损失函数
  • git学习报告
  • Spring MVC的应用
  • JavaEE: 深入探索TCP网络编程的奇妙世界(六)
  • 探秘 Web Bluetooth API:连接蓝牙设备的新利器
  • Kubernetes Pod调度基础(kubernetes)
  • Angular由一个bug说起之十:npm Unsupported engine