ReentrantLock商业项目上运用示例

欣喜 Java经验 发布时间:2025-03-21 11:15:17 阅读数:9603 1
下文笔者讲述"ReentrantLock商业项目"应用示例分享,如下所示

ReentrantLock简介

`ReentrantLock`是Java中`java.util.concurrent.locks`包
   提供一个可重入锁(Reentrant Lock)

ReentrantLock主要特性

1.可重入性:
   - 如果某个线程已经持有了 `ReentrantLock`
      它可以再次获取该锁而不被阻塞。
   - 例
      如果一个方法调用另一个也需要同一把锁的方法,不会导致死锁。

2.公平性:
   - 可以选择是否启用公平锁。
       公平锁会按照线程请求锁的顺序来分配锁,
	    而非公平锁则允许插队。
   - 默认是非公平锁
       可以通过构造函数参数`true`来
	     创建公平锁。

3.条件变量:
   - `ReentrantLock`提供`Condition`接口
       可以替代 `Object` 的 `wait()` 和 `notify()` 方法
	     提供更精细的线程控制。

4.锁中断支持:
   -`ReentrantLock`支持中断操作
     可以在等待获取锁的过程中响应中断。

ReentrantLock基本用法

创建和使用 `ReentrantLock`

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    private final ReentrantLock lock = new ReentrantLock();
    private int counter = 0;

    public void increment() {
        lock.lock();
        try {
            counter++;
        } finally {
            lock.unlock();
        }
    }

    public int getCounter() {
        return counter;
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockExample example = new ReentrantLockExample();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Counter: " + example.getCounter());
    }
}

使用公平锁

import java.util.concurrent.locks.ReentrantLock;

public class FairReentrantLockExample {
    private final ReentrantLock fairLock = new ReentrantLock(true);
    private int counter = 0;

    public void increment() {
        fairLock.lock();
        try {
            counter++;
        } finally {
            fairLock.unlock();
        }
    }

    public int getCounter() {
        return counter;
    }

    public static void main(String[] args) throws InterruptedException {
        FairReentrantLockExample example = new FairReentrantLockExample();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                example.increment();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Counter: " + example.getCounter());
    }
}

使用条件变量

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionExample {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private boolean ready = false;

    public void await() throws InterruptedException {
        lock.lock();
        try {
            while (!ready) {
                condition.await();
            }
            // 执行某些操作
            System.out.println("Condition is ready, proceeding...");
        } finally {
            lock.unlock();
        }
    }

    public void signal() {
        lock.lock();
        try {
            ready = true;
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionExample example = new ConditionExample();

        Thread t1 = new Thread(() -> {
            try {
                example.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            example.signal();
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}

ReentrantLock注意事项

1.确保在 `finally` 块中解锁:
   - 为了防止死锁,始终在 `finally` 块中释放锁。

2.避免滥用锁:
   - 锁的粒度应尽可能小,
    以减少竞争和提高并发性能。

3.处理中断:
   - 在需要响应中断的场景下,
   使用 `lockInterruptibly()` 方法来获取锁,
     并捕获 `InterruptedException`。

示例代码

以下是一个综合示例,展示了如何使用 `ReentrantLock` 和 `Condition`:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockAndConditionExample {
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();
    private int counter = 0;

    public void increment() {
        lock.lock();
        try {
            counter++;
            if (counter >= 10) {
                condition.signalAll(); // 通知所有等待的线程
            }
        } finally {
            lock.unlock();
        }
    }

    public void awaitUntilTen() throws InterruptedException {
        lock.lock();
        try {
            while (counter < 10) {
                condition.await();
            }
            // 执行某些操作
            System.out.println("Counter reached 10, proceeding...");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReentrantLockAndConditionExample example = new ReentrantLockAndConditionExample();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 15; i++) {
                example.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                example.awaitUntilTen();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202503/17425269458385.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者