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

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.xdnf.cn/news/8430.html

相关文章:

  • MyBatis 笔记:parameterType、resultType 与 resultMap 的区别详解
  • Android 网络全栈攻略(四)—— 从 OkHttp 拦截器来看 HTTP 协议一
  • 146. LRU Cache
  • Anthropic公司近日发布了两款新一代大型语言模型Claude Opus 4与Claude Sonnet 4
  • 矩阵:线性代数在AI大模型中的核心支柱
  • 深入解析MySQL中的HAVING关键字:从入门到实战
  • Docker 与 Kubernetes 部署 RabbitMQ 集群(二)
  • C++ 忘掉std::cout吧,fmt和spdlog的结合
  • 达梦数据库-报错-01-[-3205]:全文索引词库加载出错
  • paddle 打包代码 ocr
  • 国产高云FPGA实现MIPI视频解码+图像缩放,基于OV5647摄像头,提供Gowin工程源码和技术支持
  • 04-jenkins学习之旅-java后端项目部署实践
  • 攻略生成模块
  • python邮件地址检验 2024年信息素养大赛复赛/决赛真题 小学组/初中组 python编程挑战赛 真题详细解析
  • C++---vector模拟实现
  • 黑马点评-实现安全秒杀优惠券(使并发一人一单,防止并发超卖)
  • Java桌面应用开发详解:自制截图工具从设计到打包的全流程【附源码与演示】
  • LVS + Keepalived + Nginx 高可用负载均衡系统实验
  • 详解Mysql的 Binlog、UndoLog 和 RedoLog
  • 「金融证券行业」 如何搭建自己的研发智能管理体系?
  • Linux 操作文本文件列数据的常用命令
  • @Column 注解属性详解
  • 【Nature子刊聚焦:超构表面多维调控与AI驱动的设计革命 ——2024-2025年超构表面领域突破性进展速览 】
  • 职坐标解析物联网协议与传感器技术实战应用
  • MuJoCo安装记录
  • 一个基于 ESP-IDF 的 RPC over UDP 示例
  • 2025 最新 Redis 面试题大全
  • 探索服务网格(Service Mesh):云原生时代的网络新范式
  • DDR DFI 5.2 协议接口学习梳理笔记01
  • 工业软件国产化:构建自主创新生态,赋能制造强国建设