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

SkyWalking 10.2.0 SWCK 配置过程

SkyWalking 10.2.0 & SWCK 配置过程 skywalking oap-server & ui 使用Docker安装在K8S集群以外&#xff0c;K8S集群中的微服务使用initContainer按命名空间将skywalking-java-agent注入到业务容器中。 SWCK有整套的解决方案&#xff0c;全安装在K8S群集中。 具体可参…...

简易版抽奖活动的设计技术方案

1.前言 本技术方案旨在设计一套完整且可靠的抽奖活动逻辑,确保抽奖活动能够公平、公正、公开地进行,同时满足高并发访问、数据安全存储与高效处理等需求,为用户提供流畅的抽奖体验,助力业务顺利开展。本方案将涵盖抽奖活动的整体架构设计、核心流程逻辑、关键功能实现以及…...

Day131 | 灵神 | 回溯算法 | 子集型 子集

Day131 | 灵神 | 回溯算法 | 子集型 子集 78.子集 78. 子集 - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 笔者写过很多次这道题了&#xff0c;不想写题解了&#xff0c;大家看灵神讲解吧 回溯算法套路①子集型回溯【基础算法精讲 14】_哔哩哔哩_bilibili 完…...

pam_env.so模块配置解析

在PAM&#xff08;Pluggable Authentication Modules&#xff09;配置中&#xff0c; /etc/pam.d/su 文件相关配置含义如下&#xff1a; 配置解析 auth required pam_env.so1. 字段分解 字段值说明模块类型auth认证类模块&#xff0c;负责验证用户身份&am…...

macOS多出来了:Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用

文章目录 问题现象问题原因解决办法 问题现象 macOS启动台&#xff08;Launchpad&#xff09;多出来了&#xff1a;Google云端硬盘、YouTube、表格、幻灯片、Gmail、Google文档等应用。 问题原因 很明显&#xff0c;都是Google家的办公全家桶。这些应用并不是通过独立安装的…...

spring:实例工厂方法获取bean

spring处理使用静态工厂方法获取bean实例&#xff0c;也可以通过实例工厂方法获取bean实例。 实例工厂方法步骤如下&#xff1a; 定义实例工厂类&#xff08;Java代码&#xff09;&#xff0c;定义实例工厂&#xff08;xml&#xff09;&#xff0c;定义调用实例工厂&#xff…...

NFT模式:数字资产确权与链游经济系统构建

NFT模式&#xff1a;数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新&#xff1a;构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议&#xff1a;基于LayerZero协议实现以太坊、Solana等公链资产互通&#xff0c;通过零知…...

有限自动机到正规文法转换器v1.0

1 项目简介 这是一个功能强大的有限自动机&#xff08;Finite Automaton, FA&#xff09;到正规文法&#xff08;Regular Grammar&#xff09;转换器&#xff0c;它配备了一个直观且完整的图形用户界面&#xff0c;使用户能够轻松地进行操作和观察。该程序基于编译原理中的经典…...

Aspose.PDF 限制绕过方案:Java 字节码技术实战分享(仅供学习)

Aspose.PDF 限制绕过方案&#xff1a;Java 字节码技术实战分享&#xff08;仅供学习&#xff09; 一、Aspose.PDF 简介二、说明&#xff08;⚠️仅供学习与研究使用&#xff09;三、技术流程总览四、准备工作1. 下载 Jar 包2. Maven 项目依赖配置 五、字节码修改实现代码&#…...

保姆级教程:在无网络无显卡的Windows电脑的vscode本地部署deepseek

文章目录 1 前言2 部署流程2.1 准备工作2.2 Ollama2.2.1 使用有网络的电脑下载Ollama2.2.2 安装Ollama&#xff08;有网络的电脑&#xff09;2.2.3 安装Ollama&#xff08;无网络的电脑&#xff09;2.2.4 安装验证2.2.5 修改大模型安装位置2.2.6 下载Deepseek模型 2.3 将deepse…...