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

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锁问题

锁是什么,锁锁的是谁?

相关文章:

  • 【JS】Vue 3中ref与reactive的核心区别及使用场景
  • php本地 curl 请求证书问题解决
  • 业务场景中使用 SQL 实现快速数据更新与插入
  • 养生指南:五维焕新健康生活
  • PostgreSQL 处理链接请求
  • AI 驱动近红外光谱预处理:从数据清洗到特征工程的自动化
  • Selenium元素定位的8种核心方法详解
  • [特殊字符] 构建高内聚低耦合的接口架构:从数据校验到后置通知的分层实践
  • 怎么判断一个Android APP使用了Electron 这个跨端框架
  • 气象数字地球新生态:星图云全栈解决方案解析 —— 多源数据融合・精细预报・全场景落地
  • Chrome中http被强转成https问题
  • unity在urp管线中插入事件
  • 什么是软件压力测试,出压力测评报告的第三方软件检测公司推荐
  • Neo4j入门第二期(Spring Data Neo4j的使用)
  • 02-jenkins学习之旅-基础配置
  • Android计算机网络学习总结
  • Flink初始及搭建集群环境(技术选型与实战详解)
  • 音视频之视频压缩及数字视频基础概念
  • 【AI大模型研究报告】2024年中国工业大模型行业发展研究报告
  • 【信息系统项目管理师】第20章:高级项目管理 - 28个经典题目及详解
  • 网站用户注册怎么做/南宁seo优势
  • 在那里做网站/客户管理系统
  • wordpress搭建的网站能干什么/网页模板下载
  • 网站制作属于什么行业/品牌广告语
  • 番禺建设网站集团/百度seo网站优化
  • cms影视建站系统/视频互联网推广选择隐迅推