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

实现Java多线程中的线程间通信

实现Java多线程中的线程间通信

大家好,我是微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!

1. 线程间通信的基本概念

在线程编程中,线程间通信是指多个线程之间通过共享内存或消息传递的方式进行交互和协作。Java提供了多种机制来实现线程间通信,如共享对象、wait/notify机制、管道、并发集合等。

2. 使用wait和notify实现线程间通信

wait和notify是Java中基本的线程同步机制,用于在共享对象上进行等待和唤醒操作。以下是一个简单的例子,展示如何通过wait和notify实现线程间的基本通信。

package cn.juwatech.threadcommunication;public class WaitNotifyExample {public static void main(String[] args) {Message message = new Message();Thread producerThread = new Thread(new Producer(message));Thread consumerThread = new Thread(new Consumer(message));producerThread.start();consumerThread.start();}static class Message {private String content;private boolean empty = true;public synchronized String read() {while (empty) {try {wait(); // 等待生产者线程写入内容} catch (InterruptedException e) {Thread.currentThread().interrupt();}}empty = true;notifyAll(); // 唤醒其他等待线程return content;}public synchronized void write(String content) {while (!empty) {try {wait(); // 等待消费者线程读取内容} catch (InterruptedException e) {Thread.currentThread().interrupt();}}this.content = content;empty = false;notifyAll(); // 唤醒其他等待线程}}static class Producer implements Runnable {private final Message message;Producer(Message message) {this.message = message;}@Overridepublic void run() {String[] messages = {"Message 1", "Message 2", "Message 3"};for (String msg : messages) {message.write(msg);System.out.println("Produced: " + msg);try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}static class Consumer implements Runnable {private final Message message;Consumer(Message message) {this.message = message;}@Overridepublic void run() {for (int i = 0; i < 3; i++) {String msg = message.read();System.out.println("Consumed: " + msg);try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}
}

3. 使用Lock和Condition实现线程间通信

除了wait和notify,Java还提供了更灵活的Lock和Condition机制,可以更精确地控制线程的等待和唤醒。

package cn.juwatech.threadcommunication;import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class LockConditionExample {public static void main(String[] args) {Message message = new Message();Thread producerThread = new Thread(new Producer(message));Thread consumerThread = new Thread(new Consumer(message));producerThread.start();consumerThread.start();}static class Message {private String content;private boolean empty = true;private final Lock lock = new ReentrantLock();private final Condition condition = lock.newCondition();public void read() {lock.lock();try {while (empty) {try {condition.await(); // 等待生产者线程写入内容} catch (InterruptedException e) {Thread.currentThread().interrupt();}}empty = true;condition.signalAll(); // 唤醒其他等待线程System.out.println("Consumed: " + content);} finally {lock.unlock();}}public void write(String content) {lock.lock();try {while (!empty) {try {condition.await(); // 等待消费者线程读取内容} catch (InterruptedException e) {Thread.currentThread().interrupt();}}this.content = content;empty = false;condition.signalAll(); // 唤醒其他等待线程System.out.println("Produced: " + content);} finally {lock.unlock();}}}static class Producer implements Runnable {private final Message message;Producer(Message message) {this.message = message;}@Overridepublic void run() {String[] messages = {"Message 1", "Message 2", "Message 3"};for (String msg : messages) {message.write(msg);try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}static class Consumer implements Runnable {private final Message message;Consumer(Message message) {this.message = message;}@Overridepublic void run() {for (int i = 0; i < 3; i++) {message.read();try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}
}

4. 总结

通过本文的实例,你应该已经掌握了在Java多线程编程中实现线程间通信的基本方法,包括使用wait/notify和Lock/Condition机制。合理地应用这些机制可以有效地管理线程之间的协作,提升程序的并发处理能力。

微赚淘客系统3.0小编出品,必属精品,转载请注明出处!

http://www.lryc.cn/news/393760.html

相关文章:

  • C++模板元编程(一)——可变参数模板
  • kafka中
  • Android 获取当前电池状态
  • 【JVM 的内存模型】
  • 【雷丰阳-谷粒商城 】【分布式高级篇-微服务架构篇】【17】认证服务01—短信/邮件/异常/MD5
  • geom buffer制作
  • 微软正在放弃React
  • U盘非安全退出后的格式化危机与高效恢复策略
  • 安卓虚拟位置修改
  • 大数据面试题之Presto[Trino](5)
  • 对编程开发人员在今年的一些建议
  • VSCode设置好看清晰的字体!中文用鸿蒙,英文用Jetbrains Mono
  • SpringBoot新手快速入门系列教程四:创建第一个SringBoot的API
  • 第1集《修习止观坐禅法要》
  • markdown变量引用
  • 如何使用echart做K线图
  • Spring Boot应用使用GraalVM本地编译相关配置
  • 代码的坏味道——长函数
  • 【机器学习】基于密度的聚类算法:DBSCAN详解
  • Qt 网络编程 网络信息获取操作
  • linux中的进程以及进程管理
  • pyecharts可视化案例大全(11~20)
  • Docker在人工智能领域的应用与实战
  • python基础篇(8):异常处理
  • FortiClient 用IPsec VPN 远程拨号到FortiGate说明文档
  • Git-Unity项目版本管理
  • 每日一题~ leetcode 402 (贪心+单调栈)
  • 设计模式之模版方法
  • docker部署redis/mongodb/
  • LeetCode 581. 最短无序连续子数组