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

多线程应用实战

文章目录

  • 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、如何实现多线程交替打印字母和数字&#xff0c;打印效果&#xff1a;A1B2C3D4...AutomicBlockingQueueReentrantLockLockSupportSynchronizedWaitNotifyTransferQueueWay 2、实现多个线程顺序打印abc3、实现阻塞队列 1、如何实现多线程交替打印字母和数字&#xff…...

selenium解放双手--记某电力学校的刷课脚本

免责声明:本文仅做技术交流与学习... 重难点: 1-对目标网站的html框架具有很好的了解,定位元素,精准打击. 2-自动化过程中窗口操作的转换. 前置知识: python--selenium模块的操作使用 前端的html代码 验证码自动化操作 Chrome & Chromedriver : Chrome for Testing ava…...

JDK 17有可能代替 JDK 8 吗

不好说&#xff0c;去 Oracle 化是很多公司逐步推进的政策。 JVM 有 OpenJ9。很多公司可能会用 IBM 的版本。 JDK 这东西&#xff0c;能用就不会升级。 JDK 太基础了&#xff0c;决定了后面的很多 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. 代码实现 题目链接&#xff1a;3128. Right Triangles 1. 解题思路 这一题的话对于任意一个位置&#xff0c;如果该位置为1&#xff0c;假设其所在行中1的个数 r i r_i ri​&#xff0c;所在列中1的个数为 c j c_j cj​&#…...

力扣经典150题第五十三题:基本计算器

目录 力扣经典150题第五十六题&#xff1a;基本计算器示例提示解题思路 力扣经典150题第五十六题&#xff1a;基本计算器 给你一个字符串表达式 s &#xff0c;请你实现一个基本计算器来计算并返回它的值。 注意:不允许使用任何将字符串作为数学表达式计算的内置函数&#xf…...

如何为 Nestjs 编写单元测试和 E2E 测试

前言 最近在给一个 nestjs 项目写单元测试&#xff08;Unit Testing&#xff09;和 e2e 测试&#xff08;End-to-End Testing&#xff0c;端到端测试&#xff0c;简称 e2e 测试&#xff09;&#xff0c;这是我第一次给后端项目写测试&#xff0c;发现和之前给前端项目写测试还…...

基于Python的LSTM网络实现单特征预测回归任务(TensorFlow)

单特征&#xff1a;数据集中只包含2列&#xff0c;时间列价格列&#xff0c;仅利用价格来预测价格 目录 一、数据集 二、任务目标 三、代码实现 1、从本地路径中读取数据文件 2、数据归一化 3、创建配置类&#xff0c;将LSTM的各个超参数声明为变量&#xff0c;便于后续…...

Spring - 8 ( 10000 字 Spring 入门级教程 )

一&#xff1a; MyBatis 1.1 引入 MyBatis 我们学习 MySQL 数据库时&#xff0c;已经学习了 JDBC 来操作数据库, 但是 JDBC 操作太复杂了. 我们先来回顾⼀下 JDBC 的操作流程: 创建数据库连接池 DataSource通过 DataSource 获取数据库连接 Connection编写要执行带 ? 占位符…...

鸿蒙内核源码分析(忍者ninja篇) | 都忍者了能不快吗

ninja | 忍者 ninja是一个叫 Evan Martin的谷歌工程师开源的一个自定义的构建系统,最早是用于 chrome的构建,Martin给它取名 ninja(忍者)的原因是因为它strikes quickly(快速出击).这是忍者的特点,可惜Martin不了解中国文化,不然叫小李飞刀更合适些.究竟有多块呢? 用Martin自…...

Linux——守护进程化(独立于用户会话的进程)

目录 前言 一、进程组ID与会话ID 二、setsid() 创建新会话 三、daemon 守护进程 前言 在之前&#xff0c;我们学习过socket编程中的udp通信与tcp通信&#xff0c;但是当时我们服务器启动的时候&#xff0c;都是以前台进程的方式启动的&#xff0c;这样很不优雅&#xff0c…...

安卓开发--按键跳转页面,按键按下变色

前面已经介绍了一个空白按键工程的建立以及响应方式&#xff0c;可以参考这里&#xff1a;安卓开发–新建工程&#xff0c;新建虚拟手机&#xff0c;按键事件响应。 安卓开发是页面跳转是基础&#xff01;&#xff01;&#xff01;所以本篇博客介绍利用按键实现页面跳转&#…...

Ps基础学习笔记

Ps基础学习笔记 Adobe Photoshop&#xff08;简称Ps&#xff09;是一款非常流行的图像处理软件&#xff0c;被广泛应用于图像编辑、修饰和设计等领域。作为一名初学者&#xff0c;了解Ps的基础知识是非常重要的&#xff0c;本文将介绍Ps的基本操作和常用工具&#xff0c;帮助你…...

spring开发问题总结(持续更新)

开始 最近在做项目的时候&#xff0c;总遇到一些大小不一&#xff0c;奇形怪状的问题。 现在终于有时间来总结一下遇到的问题&#xff0c;以备复习之用。 以下提到的问题经过简化&#xff0c;不代表任何项目代码或问题。 问题1&#xff1a;未完成任务状态搜索结果有误&#x…...

Android 状态栏WiFi图标的显示逻辑

1. 状态栏信号图标 1.1 WIFI信号显示 WIFI信号在状态栏的显示如下图所示 当WiFi状态为关闭时&#xff0c;状态栏不会有任何显示。当WiFi状态打开时&#xff0c;会如上图所示&#xff0c;左侧表示有可用WiFi&#xff0c;右侧表示当前WiFi打开但未连接。 当WiFi状态连接时&#x…...

更改 DeepXDE 的后端

DeepXDE 库为科学计算和工程优化等领域提供了深度学习方法&#xff0c;是一个非常有用的工具。其中一个重要的功能是它允许用户自定义后端。在本文中&#xff0c;我们将指导如何更改 DeepXDE 的后端&#xff0c;并且验证更改是否成功。 更改 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&#xff1a;选择明密文攻击 关于选择明/密文攻击&#xff0c;其实这一般是打一套组合拳的&#xff0c;在网上找到了利用的思路&#xff0c;感觉下面这个题目是真正将这个问题实现了&#xff0c;所以还是非常棒的一道题&#xff0c;下面先了解一下该知识点&#xff1a;(来自…...

Pytorch基础:torch.expand() 和 torch.repeat()

在torch中&#xff0c;如果要改变某一个tensor的维度&#xff0c;可以利用view、expand、repeat、transpose和permute等方法&#xff0c;这里对这些方法的一些容易混淆的地方做个总结。 expand和repeat函数是pytorch中常用于进行张量数据复制和维度扩展的函数&#xff0c;但其…...

利用ngx_stream_return_module构建简易 TCP/UDP 响应网关

一、模块概述 ngx_stream_return_module 提供了一个极简的指令&#xff1a; return <value>;在收到客户端连接后&#xff0c;立即将 <value> 写回并关闭连接。<value> 支持内嵌文本和内置变量&#xff08;如 $time_iso8601、$remote_addr 等&#xff09;&a…...

从WWDC看苹果产品发展的规律

WWDC 是苹果公司一年一度面向全球开发者的盛会&#xff0c;其主题演讲展现了苹果在产品设计、技术路线、用户体验和生态系统构建上的核心理念与演进脉络。我们借助 ChatGPT Deep Research 工具&#xff0c;对过去十年 WWDC 主题演讲内容进行了系统化分析&#xff0c;形成了这份…...

uniapp微信小程序视频实时流+pc端预览方案

方案类型技术实现是否免费优点缺点适用场景延迟范围开发复杂度​WebSocket图片帧​定时拍照Base64传输✅ 完全免费无需服务器 纯前端实现高延迟高流量 帧率极低个人demo测试 超低频监控500ms-2s⭐⭐​RTMP推流​TRTC/即构SDK推流❌ 付费方案 &#xff08;部分有免费额度&#x…...

OpenLayers 分屏对比(地图联动)

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 地图分屏对比在WebGIS开发中是很常见的功能&#xff0c;和卷帘图层不一样的是&#xff0c;分屏对比是在各个地图中添加相同或者不同的图层进行对比查看。…...

OPENCV形态学基础之二腐蚀

一.腐蚀的原理 (图1) 数学表达式&#xff1a;dst(x,y) erode(src(x,y)) min(x,y)src(xx,yy) 腐蚀也是图像形态学的基本功能之一&#xff0c;腐蚀跟膨胀属于反向操作&#xff0c;膨胀是把图像图像变大&#xff0c;而腐蚀就是把图像变小。腐蚀后的图像变小变暗淡。 腐蚀…...

网站指纹识别

网站指纹识别 网站的最基本组成&#xff1a;服务器&#xff08;操作系统&#xff09;、中间件&#xff08;web容器&#xff09;、脚本语言、数据厍 为什么要了解这些&#xff1f;举个例子&#xff1a;发现了一个文件读取漏洞&#xff0c;我们需要读/etc/passwd&#xff0c;如…...

基于TurtleBot3在Gazebo地图实现机器人远程控制

1. TurtleBot3环境配置 # 下载TurtleBot3核心包 mkdir -p ~/catkin_ws/src cd ~/catkin_ws/src git clone -b noetic-devel https://github.com/ROBOTIS-GIT/turtlebot3.git git clone -b noetic https://github.com/ROBOTIS-GIT/turtlebot3_msgs.git git clone -b noetic-dev…...

基于Springboot+Vue的办公管理系统

角色&#xff1a; 管理员、员工 技术&#xff1a; 后端: SpringBoot, Vue2, MySQL, Mybatis-Plus 前端: Vue2, Element-UI, Axios, Echarts, Vue-Router 核心功能&#xff1a; 该办公管理系统是一个综合性的企业内部管理平台&#xff0c;旨在提升企业运营效率和员工管理水…...

多模态图像修复系统:基于深度学习的图片修复实现

多模态图像修复系统:基于深度学习的图片修复实现 1. 系统概述 本系统使用多模态大模型(Stable Diffusion Inpainting)实现图像修复功能,结合文本描述和图片输入,对指定区域进行内容修复。系统包含完整的数据处理、模型训练、推理部署流程。 import torch import numpy …...

水泥厂自动化升级利器:Devicenet转Modbus rtu协议转换网关

在水泥厂的生产流程中&#xff0c;工业自动化网关起着至关重要的作用&#xff0c;尤其是JH-DVN-RTU疆鸿智能Devicenet转Modbus rtu协议转换网关&#xff0c;为水泥厂实现高效生产与精准控制提供了有力支持。 水泥厂设备众多&#xff0c;其中不少设备采用Devicenet协议。Devicen…...