当前位置: 首页 > 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;但其…...

Vim 调用外部命令学习笔记

Vim 外部命令集成完全指南 文章目录 Vim 外部命令集成完全指南核心概念理解命令语法解析语法对比 常用外部命令详解文本排序与去重文本筛选与搜索高级 grep 搜索技巧文本替换与编辑字符处理高级文本处理编程语言处理其他实用命令 范围操作示例指定行范围处理复合命令示例 实用技…...

电脑插入多块移动硬盘后经常出现卡顿和蓝屏

当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时&#xff0c;可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案&#xff1a; 1. 检查电源供电问题 问题原因&#xff1a;多块移动硬盘同时运行可能导致USB接口供电不足&#x…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

【MATLAB代码】基于最大相关熵准则(MCC)的三维鲁棒卡尔曼滤波算法(MCC-KF),附源代码|订阅专栏后可直接查看

文章所述的代码实现了基于最大相关熵准则(MCC)的三维鲁棒卡尔曼滤波算法(MCC-KF),针对传感器观测数据中存在的脉冲型异常噪声问题,通过非线性加权机制提升滤波器的抗干扰能力。代码通过对比传统KF与MCC-KF在含异常值场景下的表现,验证了后者在状态估计鲁棒性方面的显著优…...

(一)单例模式

一、前言 单例模式属于六大创建型模式,即在软件设计过程中,主要关注创建对象的结果,并不关心创建对象的过程及细节。创建型设计模式将类对象的实例化过程进行抽象化接口设计,从而隐藏了类对象的实例是如何被创建的,封装了软件系统使用的具体对象类型。 六大创建型模式包括…...

Linux系统部署KES

1、安装准备 1.版本说明V008R006C009B0014 V008&#xff1a;是version产品的大版本。 R006&#xff1a;是release产品特性版本。 C009&#xff1a;是通用版 B0014&#xff1a;是build开发过程中的构建版本2.硬件要求 #安全版和企业版 内存&#xff1a;1GB 以上 硬盘&#xf…...

【前端异常】JavaScript错误处理:分析 Uncaught (in promise) error

在前端开发中&#xff0c;JavaScript 异常是不可避免的。随着现代前端应用越来越多地使用异步操作&#xff08;如 Promise、async/await 等&#xff09;&#xff0c;开发者常常会遇到 Uncaught (in promise) error 错误。这个错误是由于未正确处理 Promise 的拒绝&#xff08;r…...

Vue 模板语句的数据来源

&#x1f9e9; Vue 模板语句的数据来源&#xff1a;全方位解析 Vue 模板&#xff08;<template> 部分&#xff09;中的表达式、指令绑定&#xff08;如 v-bind, v-on&#xff09;和插值&#xff08;{{ }}&#xff09;都在一个特定的作用域内求值。这个作用域由当前 组件…...

SQL Server 触发器调用存储过程实现发送 HTTP 请求

文章目录 需求分析解决第 1 步:前置条件,启用 OLE 自动化方式 1:使用 SQL 实现启用 OLE 自动化方式 2:Sql Server 2005启动OLE自动化方式 3:Sql Server 2008启动OLE自动化第 2 步:创建存储过程第 3 步:创建触发器扩展 - 如何调试?第 1 步:登录 SQL Server 2008第 2 步…...

ThreadLocal 源码

ThreadLocal 源码 此类提供线程局部变量。这些变量不同于它们的普通对应物&#xff0c;因为每个访问一个线程局部变量的线程&#xff08;通过其 get 或 set 方法&#xff09;都有自己独立初始化的变量副本。ThreadLocal 实例通常是类中的私有静态字段&#xff0c;这些类希望将…...