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

Lock与ReentrantLock

在 Java 中,Lock 接口和 ReentrantLock 类提供了比使用 synchronized 方法和代码块更广泛的锁定机制。
在这里插入图片描述
在这里插入图片描述
简单示例:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class ReentrantLockExample {private final Lock lock = new ReentrantLock();private int counter = 0;public void increment() {lock.lock();try {counter++;} finally {lock.unlock();}}public int getCounter() {lock.lock();try {return counter;} finally {lock.unlock();}}public static void main(String[] args) {ReentrantLockExample example = new ReentrantLockExample();example.increment();System.out.println("Counter: " + example.getCounter());}
}

生产者-消费者示例:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.LinkedList;
import java.util.Queue;public class ProducerConsumer {private final Queue<Integer> queue = new LinkedList<>();private final int CAPACITY = 5;private final Lock lock = new ReentrantLock();private final Condition notFull = lock.newCondition();private final Condition notEmpty = lock.newCondition();public void produce() throws InterruptedException {int value = 0;while (true) {lock.lock();try {while (queue.size() == CAPACITY) {notFull.await();}queue.add(value);System.out.println("Produced " + value);value++;notEmpty.signal();} finally {lock.unlock();}Thread.sleep(1000); // Simulate time taken to produce an item}}public void consume() throws InterruptedException {while (true) {lock.lock();try {while (queue.isEmpty()) {notEmpty.await();}int value = queue.poll();System.out.println("Consumed " + value);notFull.signal();} finally {lock.unlock();}Thread.sleep(1500); // Simulate time taken to consume an item}}public static void main(String[] args) {ProducerConsumer pc = new ProducerConsumer();Thread producerThread = new Thread(() -> {try {pc.produce();} catch (InterruptedException e) {Thread.currentThread().interrupt();}});Thread consumerThread = new Thread(() -> {try {pc.consume();} catch (InterruptedException e) {Thread.currentThread().interrupt();}});producerThread.start();consumerThread.start();}
}
http://www.lryc.cn/news/394026.html

相关文章:

  • ARM/Linux嵌入式面经(十三):紫光同芯嵌入式
  • 名企面试必问30题(二十四)—— 说说你空窗期做了什么?
  • 基础权限储存
  • Could not find a package configuration file provided by “roscpp“ 的参考解决方法
  • 运维系列.Nginx配置中的高级指令和流程控制
  • Virtualbox和ubuntu之间的关系
  • 【在Linux世界中追寻伟大的One Piece】HTTPS协议原理
  • 【WebRTC实现点对点视频通话】
  • 【Unity】RPG2D龙城纷争(八)寻路系统
  • C++ 函数高级——函数重载——基本语法
  • Go语言实现的端口扫描工具示例
  • SpringSecurity初始化过程
  • Python爬取股票信息-并进行数据可视化分析,绘股票成交量柱状图
  • 秋招突击——7/4——复习{}——新作{最长公共子序列、编辑距离、买股票最佳时机、跳跃游戏}
  • udp发送数据如果超过1个mtu时,抓包所遇到的问题记录说明
  • 电子电气架构 --- 智能座舱万物互联
  • 笔记本电脑内存不够
  • Vue项目使用mockjs模拟后端接口
  • Linux下使用arping检测IP地址是否冲突
  • 为什么 npm run serve 正常,npm run build 就报错:digital envelope routines::unsupported
  • 模电基础 - 简介
  • uniapp中实现瀑布流 短视频页面展示
  • python-开关灯(赛氪OJ)
  • 基于改进高斯-拉普拉斯滤波器的一维时间序列平滑与降噪(MATLAB)
  • 计算组的妙用!!页面权限控制
  • Self-Instruct构造Prompt的例子
  • 友好前端vue脚手架
  • SQL Server特性
  • 华为HCIP Datacom H12-821 卷25
  • 如何在 Selenium Python 中解决验证码 | 2024 完整指南