说一下线程之间是如何通信的?

1 个回答

  • 辰南
    今朝有酒今朝醉,明日愁来明日愁。
    线程之间的通信主要有两种方式:共享内存和消息传递。 ### 1. 共享内存 在共享内存的并发模型中,线程之间共享程序的公共状态,线程通过写-读内存中的公共状态来隐式进行通信。典型的共享内存通信方式是通过共享对象进行通信。 #### 通信步骤: - **线程 A** 把本地内存 A 更新过的共享变量刷新到主内存中。 - **线程 B** 到主内存中读取线程 A 之前更新过的共享变量。 #### 示例代码: ```java class SharedResource { private int value; public synchronized void setValue(int value) { this.value = value; } public synchronized int getValue() { return this.value; } } public class SharedMemoryExample { public static void main(String[] args) { SharedResource resource = new SharedResource(); Thread threadA = new Thread(() -> { resource.setValue(42); }); Thread threadB = new Thread(() -> { System.out.println(resource.getValue()); }); threadA.start(); threadB.start(); } } ``` ### 2. 消息传递 在消息传递的并发模型中,线程之间没有公共状态,线程通过明确的发送消息来显式进行通信。在 Java 中,典型的消息传递方式是使用 `wait()` 和 `notify()` 方法。 #### 通信步骤: - 线程 A 在需要发送消息时调用 `notify()` 方法。 - 线程 B 在等待消息时调用 `wait()` 方法。 #### 示例代码: ```java class Message { private String content; private boolean available = false; public synchronized void setMessage(String content) { while (available) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } this.content = content; available = true; notifyAll(); } public synchronized String getMessage() { while (!available) { try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } available = false; notifyAll(); return content; } } public class MessagePassingExample { public static void main(String[] args) { Message message = new Message(); Thread producer = new Thread(() -> { message.setMessage("Hello, World!"); }); Thread consumer = new Thread(() -> { System.out.println(message.getMessage()); }); producer.start(); consumer.start(); } } ``` ### 总结 - **共享内存**:通过共享对象在主内存中写-读公共状态来隐式通信。 - 示例:共享对象、同步方法。 - **消息传递**:线程通过发送和接收消息进行显式通信。 - 示例:使用 `wait()` 和 `notify()` 方法。 这两种通信方式各有优劣,选择时需根据具体需求和场景来确定。
    发布于 2024-07-22 09:24 •IP属地 黑龙江
    举报
    评论
    收藏