java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java ReentrantLock

Java并发编程之ReentrantLock的实现示例

作者:Johnny Lnex

本文主要介绍了Java并发编程之ReentrantLock的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、可中断锁

1. 核心方法:lockInterruptibly()

2. 代码示例

ReentrantLock lock = new ReentrantLock();

Thread thread = new Thread(() -> {
    try {
        lock.lockInterruptibly(); // 可中断获取锁
        try {
            System.out.println("线程获取锁并执行任务");
            Thread.sleep(5000); // 模拟耗时操作
        } finally {
            lock.unlock();
        }
    } catch (InterruptedException e) {
        System.out.println("线程被中断,放弃获取锁");
    }
});

lock.lock(); // 主线程先获取锁
try {
    thread.start();
    Thread.sleep(1000); // 确保子线程开始等待锁
    thread.interrupt(); // 中断子线程
} finally {
    lock.unlock();
}

3. 行为分析

二、锁超时

1. 核心方法:tryLock()

2. 代码示例:避免死锁

ReentrantLock lockA = new ReentrantLock();
ReentrantLock lockB = new ReentrantLock();

Thread thread1 = new Thread(() -> {
    try {
        if (lockA.tryLock(1, TimeUnit.SECONDS)) { // 尝试获取lockA
            try {
                if (lockB.tryLock(1, TimeUnit.SECONDS)) { // 尝试获取lockB
                    System.out.println("Thread1完成任务");
                }
            } finally {
                if (lockB.isHeldByCurrentThread()) lockB.unlock();
            }
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (lockA.isHeldByCurrentThread()) lockA.unlock();
    }
});

Thread thread2 = new Thread(() -> { /* 类似逻辑,先尝试lockB再lockA */ });
thread1.start();
thread2.start();

3. 应用场景

三、条件变量

1. 核心机制

2. 代码示例:生产者-消费者模型

ReentrantLock lock = new ReentrantLock();
Condition notEmpty = lock.newCondition(); // 非空条件
Condition notFull = lock.newCondition();  // 非满条件
Queue<Integer> queue = new LinkedList<>();
int maxSize = 10;

// 生产者
new Thread(() -> {
    lock.lock();
    try {
        while (queue.size() == maxSize) {
            notFull.await(); // 等待队列非满
        }
        queue.add(1);
        notEmpty.signal(); // 通知消费者
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}).start();

// 消费者
new Thread(() -> {
    lock.lock();
    try {
        while (queue.isEmpty()) {
            notEmpty.await(); // 等待队列非空
        }
        queue.poll();
        notFull.signal(); // 通知生产者
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}).start();

3. 优势对比wait()/notify()

特性Conditionwait()/notify()
多条件支持✅ 可创建多个条件变量❌ 每个对象仅一个等待队列
精准唤醒✅ signal() 唤醒指定条件队列的线程❌ notify() 随机唤醒

四、关键注意事项

1. 锁释放

2. 中断处理

到此这篇关于Java并发编程之ReentrantLock的实现示例的文章就介绍到这了,更多相关Java ReentrantLock内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文