您好,登录后才能下订单哦!
密码登录
            
            
            
            
        登录注册
            
            
            
        点击 登录注册 即表示同意《亿速云用户服务条款》
        # Java如何在两个线程间进行通讯
## 引言
在多线程编程中,线程间的通信(Inter-Thread Communication)是核心问题之一。Java提供了多种机制实现线程间数据传递和协调,包括共享内存、等待/通知机制、阻塞队列等。本文将深入探讨这些方法及其适用场景。
---
## 一、共享内存(Shared Memory)
### 1.1 基本原理
通过共享对象或变量实现数据交换,需配合`synchronized`保证线程安全。
```java
class SharedObject {
    private String message;
    
    public synchronized void setMessage(String msg) {
        this.message = msg;
    }
    
    public synchronized String getMessage() {
        return message;
    }
}
wait(): 释放锁并进入等待状态notify()/notifyAll(): 唤醒等待线程class MessageQueue {
    private String message;
    private boolean empty = true;
    public synchronized void put(String msg) {
        while (!empty) wait();
        message = msg;
        empty = false;
        notifyAll();
    }
    public synchronized String take() {
        while (empty) wait();
        empty = true;
        notifyAll();
        return message;
    }
}
notifyAll()避免信号丢失BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);
// 生产者线程
queue.put("Data");
// 消费者线程
String data = queue.take();
面向字节流/字符流的单向通信:
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
// 线程1写入
pos.write("Hello".getBytes());
// 线程2读取
pis.read();
CountDownLatch latch = new CountDownLatch(2);
// 线程A/B
latch.countDown();
// 主线程
latch.await();
CyclicBarrier barrier = new CyclicBarrier(3);
// 所有线程到达屏障后继续执行
barrier.await();
Exchanger<String> exchanger = new Exchanger<>();
// 线程A
String dataA = exchanger.exchange("DataA");
// 线程B
String dataB = exchanger.exchange("DataB");
class ProducerConsumer {
    private final BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(5);
    class Producer implements Runnable {
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    queue.put(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
    class Consumer implements Runnable {
        public void run() {
            try {
                while (true) {
                    Integer value = queue.take();
                    System.out.println("Consumed: " + value);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
| 方法 | 适用场景 | 线程安全 | 复杂度 | 
|---|---|---|---|
| 共享内存 | 简单数据交换 | 需同步 | 中 | 
| Wait/Notify | 精确控制执行顺序 | 是 | 高 | 
| BlockingQueue | 生产者-消费者模式 | 是 | 低 | 
| 管道 | 流式数据处理 | 是 | 中 | 
| 并发工具类 | 复杂同步场景 | 是 | 中 | 
java.util.concurrent包中的工具类Thread.stop()等废弃方法InterruptedExceptionvolatile保证可见性Lock和Condition替代synchronizedJava线程通信的选择取决于具体场景需求。对于简单交互,共享变量或BlockingQueue可能足够;复杂协调则需要Wait/Notify或并发工具类。理解每种机制的底层原理是写出健壮多线程程序的关键。
提示:Java 21引入的虚拟线程(Virtual Threads)进一步简化了并发编程模型,值得关注。 “`
(全文约1350字,可根据需要调整具体实现细节或扩展案例部分)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。