织梦网站模板教程,网站设计与制作培训学校,包头网站,wordpress后台打开时间长文章目录 使用 synchronized 的场景使用 ReentrantLock 的场景综合考虑 使用 synchronized 的场景
synchronized 是 Java 内置的同步机制#xff0c;使用起来比较简单且常用于如下场景#xff1a;
1、简单的同步逻辑#xff1a;当你的同步逻辑非常简单#xff0c;比如只需… 文章目录 使用 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 fairness3、需要条件变量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 提供更强大的功能。