多线程应用实战
文章目录
- 1、如何实现多线程交替打印字母和数字,打印效果:A1B2C3D4...
- Automic
- BlockingQueue
- ReentrantLock
- LockSupport
- SynchronizedWaitNotify
- TransferQueueWay
- 2、实现多个线程顺序打印abc
- 3、实现阻塞队列
1、如何实现多线程交替打印字母和数字,打印效果:A1B2C3D4…
Automic
public class AutomicWay {volatile static char num1 = 'A';volatile static int num2 = 1;static AtomicInteger atomicInteger = new AtomicInteger(1);public static void main(String[] args) {new Thread(() -> {for (int i = 0; i < 26; i++) {while (atomicInteger.get() != 1) {}System.out.print(num1++);atomicInteger.set(2);}}).start();new Thread(() -> {for (int i = 0; i < 26; i++) {while (atomicInteger.get() != 2) {}System.out.print(num2++);atomicInteger.set(1);}}).start();}
}
BlockingQueue
public class BlockingQueueWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {BlockingQueue queue1 = new ArrayBlockingQueue(1);BlockingQueue queue2 = new ArrayBlockingQueue(1);new Thread(() -> {try {for (int i = 0; i < 26; i++) {System.out.print(num1++);queue2.put("到你");queue1.take();}} catch (InterruptedException e) {e.printStackTrace();}}).start();new Thread(() -> {try {for (int i = 0; i < 26; i++) {queue2.take();System.out.print(num2++);queue1.put("到你");}} catch (InterruptedException e) {e.printStackTrace();}}).start();}
}
ReentrantLock
public class ConditionWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {ReentrantLock lock = new ReentrantLock();Condition conditionA = lock.newCondition();Condition conditionB = lock.newCondition();new Thread(() -> {try {lock.lock();for (int i = 0; i < 26; i++) {System.out.print(num1++);conditionB.signal();conditionA.await();}conditionB.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}).start();new Thread(() -> {try {lock.lock();for (int i = 0; i < 26; i++) {System.out.print(num2++);conditionA.signal();conditionB.await();}conditionA.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}).start();}
}
LockSupport
public class LockSupportWay {static Thread t1,t2 =null;volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {t1 = new Thread(()->{for (int i = 0; i < 26; i++) {System.out.print(num1++);LockSupport.unpark(t2);LockSupport.park(t1);}});t2 = new Thread(()->{for (int i = 0; i < 26; i++) {LockSupport.park(t2);System.out.print(num2++);LockSupport.unpark(t1);}});t1.start();t2.start();}
}
SynchronizedWaitNotify
public class SyncWaitNotifyWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static volatile boolean flag = false;public static void main(String[] args) {Object o = new Object();new Thread(()->{synchronized (o){flag = true;for (int i = 0; i < 26; i++) {System.out.print(num1++);try {o.notify();o.wait();} catch (InterruptedException e) {e.printStackTrace();}}o.notify();}}).start();new Thread(()->{synchronized (o){// 只是为了保证执行A的先跑// while (!flag){// try {// o.wait();// } catch (InterruptedException e) {// e.printStackTrace();// }// }for (int i = 0; i < 26; i++) {System.out.print(num2++);try {o.notify();o.wait();} catch (InterruptedException e) {e.printStackTrace();}}o.notify();}}).start();}
}
TransferQueueWay
public class TransferQueueWay {volatile static char num1 = 'A';volatile static int num2 = 1;public static void main(String[] args) {TransferQueue transferQueue = new LinkedTransferQueue();new Thread(() -> {try {for (int i = 0; i < 26; i++) {System.out.print(transferQueue.take());transferQueue.transfer(num2++);}} catch (InterruptedException e) {e.printStackTrace();}}).start();new Thread(() -> {try {for (int i = 0; i < 26; i++) {transferQueue.transfer(num1++);System.out.print(transferQueue.take());}} catch (InterruptedException e) {e.printStackTrace();}}).start();}}
2、实现多个线程顺序打印abc
核心代码
public class PrintABC {ReentrantLock lock = new ReentrantLock();Condition conditionA = lock.newCondition();Condition conditionB = lock.newCondition();Condition conditionC = lock.newCondition();private int count;public PrintABC(int count) {this.count = count;}volatile int value = 0;public void printABC() {new Thread(new ThreadA()).start();new Thread(new ThreadB()).start();new Thread(new ThreadC()).start();}class ThreadA implements Runnable {@Overridepublic void run() {lock.lock();try {for (int i = 0; i < count; i++) {while (value % 3 != 0) {conditionA.await();}System.out.print("A");conditionB.signal();value++;}} catch (InterruptedException e) {e.printStackTrace();}}}class ThreadB implements Runnable {@Overridepublic void run() {lock.lock();try {for (int i = 0; i < count; i++) {while (value % 3 != 1) {conditionB.await();}System.out.print("B");conditionC.signal();value++;}} catch (InterruptedException e) {e.printStackTrace();}}}class ThreadC implements Runnable {@Overridepublic void run() {lock.lock();try {for (int i = 0; i < count; i++) {while (value % 3 != 2) {conditionC.await();}System.out.print("C");conditionA.signal();value++;}} catch (InterruptedException e) {e.printStackTrace();}}}
}
测试代码
public static void main(String[] args) {PrintABC printABC = new PrintABC(10);printABC.printABC();
}// 输出结果:ABCABCABCABCABCABCABCABCABCA
3、实现阻塞队列
核心代码
public class ProviderConsumer<T> {private int length;private Queue<T> queue;private ReentrantLock lock = new ReentrantLock();private Condition provideCondition = lock.newCondition();private Condition consumeCondition = lock.newCondition();public ProviderConsumer(int length) {this.length = length;this.queue = new LinkedList<>();}public void provide(T product) {lock.lock();try {while (queue.size() >= length) { // 不能换成if,唤醒后,可能条件已经不满足了provideCondition.await();}queue.add(product);consumeCondition.signal();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}public T consume() {lock.lock();try {while (queue.isEmpty()) { // 不能换成if,唤醒后,可能条件已经不满足了consumeCondition.await();}T product = queue.remove();provideCondition.signal();return product;} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}return null;}
}
测试代码
public static void main(String[] args) {ProviderConsumer<Integer> providerConsumer = new ProviderConsumer<>(5);new Thread(() -> {for (int i = 0; i < 10; i++) {providerConsumer.provide(1);}}).start();new Thread(() -> {for (int i = 0; i < 10; i++) {providerConsumer.provide(2);}}).start();new Thread(() -> {for (int i = 0; i < 100; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(providerConsumer.consume());}}).start();
}
相关文章:
多线程应用实战
文章目录 1、如何实现多线程交替打印字母和数字,打印效果:A1B2C3D4...AutomicBlockingQueueReentrantLockLockSupportSynchronizedWaitNotifyTransferQueueWay 2、实现多个线程顺序打印abc3、实现阻塞队列 1、如何实现多线程交替打印字母和数字ÿ…...
selenium解放双手--记某电力学校的刷课脚本
免责声明:本文仅做技术交流与学习... 重难点: 1-对目标网站的html框架具有很好的了解,定位元素,精准打击. 2-自动化过程中窗口操作的转换. 前置知识: python--selenium模块的操作使用 前端的html代码 验证码自动化操作 Chrome & Chromedriver : Chrome for Testing ava…...
JDK 17有可能代替 JDK 8 吗
不好说,去 Oracle 化是很多公司逐步推进的政策。 JVM 有 OpenJ9。很多公司可能会用 IBM 的版本。 JDK 这东西,能用就不会升级。 JDK 太基础了,决定了后面的很多 jar 的版本。 https://www.ossez.com/t/jdk-17-jdk-8/14102...
代码随想录算法训练营第36期DAY23
DAY23 530二叉搜索树的最小绝对差 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(null…...
Leetcode 3128. Right Triangles
Leetcode 3128. Right Triangles 1. 解题思路2. 代码实现 题目链接:3128. Right Triangles 1. 解题思路 这一题的话对于任意一个位置,如果该位置为1,假设其所在行中1的个数 r i r_i ri,所在列中1的个数为 c j c_j cj&#…...
力扣经典150题第五十三题:基本计算器
目录 力扣经典150题第五十六题:基本计算器示例提示解题思路 力扣经典150题第五十六题:基本计算器 给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。 注意:不允许使用任何将字符串作为数学表达式计算的内置函数…...
如何为 Nestjs 编写单元测试和 E2E 测试
前言 最近在给一个 nestjs 项目写单元测试(Unit Testing)和 e2e 测试(End-to-End Testing,端到端测试,简称 e2e 测试),这是我第一次给后端项目写测试,发现和之前给前端项目写测试还…...
基于Python的LSTM网络实现单特征预测回归任务(TensorFlow)
单特征:数据集中只包含2列,时间列价格列,仅利用价格来预测价格 目录 一、数据集 二、任务目标 三、代码实现 1、从本地路径中读取数据文件 2、数据归一化 3、创建配置类,将LSTM的各个超参数声明为变量,便于后续…...
Spring - 8 ( 10000 字 Spring 入门级教程 )
一: MyBatis 1.1 引入 MyBatis 我们学习 MySQL 数据库时,已经学习了 JDBC 来操作数据库, 但是 JDBC 操作太复杂了. 我们先来回顾⼀下 JDBC 的操作流程: 创建数据库连接池 DataSource通过 DataSource 获取数据库连接 Connection编写要执行带 ? 占位符…...
鸿蒙内核源码分析(忍者ninja篇) | 都忍者了能不快吗
ninja | 忍者 ninja是一个叫 Evan Martin的谷歌工程师开源的一个自定义的构建系统,最早是用于 chrome的构建,Martin给它取名 ninja(忍者)的原因是因为它strikes quickly(快速出击).这是忍者的特点,可惜Martin不了解中国文化,不然叫小李飞刀更合适些.究竟有多块呢? 用Martin自…...
Linux——守护进程化(独立于用户会话的进程)
目录 前言 一、进程组ID与会话ID 二、setsid() 创建新会话 三、daemon 守护进程 前言 在之前,我们学习过socket编程中的udp通信与tcp通信,但是当时我们服务器启动的时候,都是以前台进程的方式启动的,这样很不优雅,…...
安卓开发--按键跳转页面,按键按下变色
前面已经介绍了一个空白按键工程的建立以及响应方式,可以参考这里:安卓开发–新建工程,新建虚拟手机,按键事件响应。 安卓开发是页面跳转是基础!!!所以本篇博客介绍利用按键实现页面跳转&#…...
Ps基础学习笔记
Ps基础学习笔记 Adobe Photoshop(简称Ps)是一款非常流行的图像处理软件,被广泛应用于图像编辑、修饰和设计等领域。作为一名初学者,了解Ps的基础知识是非常重要的,本文将介绍Ps的基本操作和常用工具,帮助你…...
spring开发问题总结(持续更新)
开始 最近在做项目的时候,总遇到一些大小不一,奇形怪状的问题。 现在终于有时间来总结一下遇到的问题,以备复习之用。 以下提到的问题经过简化,不代表任何项目代码或问题。 问题1:未完成任务状态搜索结果有误&#x…...
Android 状态栏WiFi图标的显示逻辑
1. 状态栏信号图标 1.1 WIFI信号显示 WIFI信号在状态栏的显示如下图所示 当WiFi状态为关闭时,状态栏不会有任何显示。当WiFi状态打开时,会如上图所示,左侧表示有可用WiFi,右侧表示当前WiFi打开但未连接。 当WiFi状态连接时&#x…...
更改 DeepXDE 的后端
DeepXDE 库为科学计算和工程优化等领域提供了深度学习方法,是一个非常有用的工具。其中一个重要的功能是它允许用户自定义后端。在本文中,我们将指导如何更改 DeepXDE 的后端,并且验证更改是否成功。 更改 DeepXDE 的后端 DeepXDE 支持多种…...
SpringBoot之Zuul服务
概述 Spring Cloud Netflix zuul组件是微服务架构中的网关组件,Zuul作为统一网关,是所有访问该平台的请求入口,核心功能是路由和过滤。 目前公司业务就是基于Zuul搭建的网关服务,且提供的服务包括转发请求(路由)、黑名单IP访问拦截、URL资源访问时的权限拦截、统一访问日志记…...
Go-变量
可以理解为一个昵称 以后这个昵称就代指这些信息 var sg string "czy" 声明赋值 package mainimport "fmt"func main() {var sg string "陈政洋"fmt.Println(sg)var age int 73fmt.Println(age)var flag bool truefmt.Println(flag) } …...
【CTF-Crypto】RSA-选择明密文攻击 一文通
RSA:选择明密文攻击 关于选择明/密文攻击,其实这一般是打一套组合拳的,在网上找到了利用的思路,感觉下面这个题目是真正将这个问题实现了,所以还是非常棒的一道题,下面先了解一下该知识点:(来自…...
Pytorch基础:torch.expand() 和 torch.repeat()
在torch中,如果要改变某一个tensor的维度,可以利用view、expand、repeat、transpose和permute等方法,这里对这些方法的一些容易混淆的地方做个总结。 expand和repeat函数是pytorch中常用于进行张量数据复制和维度扩展的函数,但其…...
Spring Boot 实现流式响应(兼容 2.7.x)
在实际开发中,我们可能会遇到一些流式数据处理的场景,比如接收来自上游接口的 Server-Sent Events(SSE) 或 流式 JSON 内容,并将其原样中转给前端页面或客户端。这种情况下,传统的 RestTemplate 缓存机制会…...
云启出海,智联未来|阿里云网络「企业出海」系列客户沙龙上海站圆满落地
借阿里云中企出海大会的东风,以**「云启出海,智联未来|打造安全可靠的出海云网络引擎」为主题的阿里云企业出海客户沙龙云网络&安全专场于5.28日下午在上海顺利举办,现场吸引了来自携程、小红书、米哈游、哔哩哔哩、波克城市、…...
Python爬虫实战:研究feedparser库相关技术
1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…...
Mac软件卸载指南,简单易懂!
刚和Adobe分手,它却总在Library里给你写"回忆录"?卸载的Final Cut Pro像电子幽灵般阴魂不散?总是会有残留文件,别慌!这份Mac软件卸载指南,将用最硬核的方式教你"数字分手术"࿰…...
GitHub 趋势日报 (2025年06月08日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...
IT供电系统绝缘监测及故障定位解决方案
随着新能源的快速发展,光伏电站、储能系统及充电设备已广泛应用于现代能源网络。在光伏领域,IT供电系统凭借其持续供电性好、安全性高等优势成为光伏首选,但在长期运行中,例如老化、潮湿、隐裂、机械损伤等问题会影响光伏板绝缘层…...
自然语言处理——循环神经网络
自然语言处理——循环神经网络 循环神经网络应用到基于机器学习的自然语言处理任务序列到类别同步的序列到序列模式异步的序列到序列模式 参数学习和长程依赖问题基于门控的循环神经网络门控循环单元(GRU)长短期记忆神经网络(LSTM)…...
处理vxe-table 表尾数据是单独一个接口,表格tableData数据更新后,需要点击两下,表尾才是正确的
修改bug思路: 分别把 tabledata 和 表尾相关数据 console.log() 发现 更新数据先后顺序不对 settimeout延迟查询表格接口 ——测试可行 升级↑:async await 等接口返回后再开始下一个接口查询 ________________________________________________________…...
Redis:现代应用开发的高效内存数据存储利器
一、Redis的起源与发展 Redis最初由意大利程序员Salvatore Sanfilippo在2009年开发,其初衷是为了满足他自己的一个项目需求,即需要一个高性能的键值存储系统来解决传统数据库在高并发场景下的性能瓶颈。随着项目的开源,Redis凭借其简单易用、…...
苹果AI眼镜:从“工具”到“社交姿态”的范式革命——重新定义AI交互入口的未来机会
在2025年的AI硬件浪潮中,苹果AI眼镜(Apple Glasses)正在引发一场关于“人机交互形态”的深度思考。它并非简单地替代AirPods或Apple Watch,而是开辟了一个全新的、日常可接受的AI入口。其核心价值不在于功能的堆叠,而在于如何通过形态设计打破社交壁垒,成为用户“全天佩戴…...
