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

JUC并发编程1

什么是juc

在java的java.util.concurrent包下的工具。
juc

传统的synchronize

public class SealTicket {int total = 50;public synchronized void seal() {if (total > 0) {System.out.println(Thread.currentThread().getName()+ "卖出第"+ (total--)+ "张,剩余:" + total);}}
}

JUC 的锁

public class SealTicket {int total = 50;Lock lock = new ReentrantLock();public void seal() {lock.lock();if (total > 0) {System.out.println(Thread.currentThread().getName()+ "卖出第"+ (total--)+ "张,剩余:" + total);}lock.unlock();}
}

Synchronize 和 Lock的区别

在这里插入图片描述

生产者和消费者问题

版本 synchronize

public class Data {int i = 0;public synchronized void add() throws InterruptedException {if (i != 0) {this.wait();}i++;System.out.println(Thread.currentThread().getName() + "=="+ i);this.notifyAll();}public synchronized void remove() throws InterruptedException {if (i == 0) {this.wait();}i--;System.out.println(Thread.currentThread().getName() + "=="+ i);this.notifyAll();}
}public class Producer {public static void main(String[] args) {Data data = new Data();new Thread(() -> {for (int i = 0; i < 60; i++) {try {data.add();} catch (InterruptedException e) {throw new RuntimeException(e);}}}, "a").start();new Thread(() -> {for (int i = 0; i < 60; i++) {try {data.remove();} catch (InterruptedException e) {throw new RuntimeException(e);}}}, "b").start();//        new Thread(() -> {
//            for (int i = 0; i < 60; i++) {
//                sealTicket.seal();
//            }
//        }, "c").start();}
}

版本 Lock

8锁问题

锁是什么,锁锁的是谁?

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

相关文章:

  • 消息队列RabbitMQ与AMQP协议详解
  • Day 29 训练
  • STM32开发环境配置——VSCode+PlatformIO + CubeMX + FreeRTOS的集成环境配置
  • Profibus转Profinet网关赋能鼓式硫化机:智能化生产升级的关键突破
  • redis 缓存穿透,缓存雪崩,缓存击穿
  • JAVA8怎么使用9的List.of
  • 告别手动测试:AUTOSAR网络管理自动化测试实战
  • BUCK电路利用状态空间平均法和开关周期平均法推导
  • MongoDB 用户与权限管理完全指南
  • C++滑动门问题(附两种方法)
  • 基于ITcpServer/IHttpServer框架的HTTP服务器
  • 初识main函数
  • FPGA高效验证工具Solidify 8.0:全面重构图形用户界面
  • SIL2/PLd 认证 Inxpect毫米波安全雷达:3D 扫描 + 微小运动检测守护工业安全
  • java中string类型的list集合放到redis的5种数据类型的那种比较合适呢,可以用StringRedisTemplate实现
  • PyQt学习系列09-应用程序打包与部署
  • 实现图片自动压缩算法,canvas压缩图片方法
  • 《数据结构笔记三》:单链表(创建、插入、遍历、删除、释放内存等核心操作)
  • 光伏行业如何利用SD-WAN优化分布式网络:替代MPLS、VPN、4G/5G的网络架构升级与云安全方案全解析
  • 2025电工杯数学建模A题思路数模AI提示词工程
  • LLM | 论文精读 | NAACL 2025 | Clarify When Necessary:教语言模型何时该“问一句”再答!
  • 嵌入式鸿蒙openharmony应用开发环境搭建与工程创建实现
  • MDK的编译过程及文件类型全解
  • socc 19 echash论文部分解读
  • Linux Shell编程(八)
  • AI筑基,新质跃升|英码科技亮相华为广东新质生产力创新峰会,发布大模型一体机新品,助力产业智能化转型
  • 手机打电话时由对方DTMF响应切换多级IVR语音菜单(话术脚本与实战)
  • 面试题——JDBC|Maven|Spring的IOC思想|DI思想|SpringMVC
  • DETR3D- 3D Object Detection from Multi-view Images via 3D-to-2D Queries
  • SpringBoot3整合WebSocket