Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Concurrency
并发

What you’ll learn: How Rust concurrency compares to Java threads, executors, and synchronized shared state.
本章将学习: Rust 并发模型如何对应 Java 线程、执行器以及同步共享状态。

Difficulty: 🔴 Advanced
难度: 🔴 高级

Java gives teams mature concurrency tools. Rust brings a different advantage: the compiler participates more directly in preventing misuse.
Java 已经给团队提供了非常成熟的并发工具,而 Rust 的优势则落在另一边:编译器会更直接地参与阻止误用。

Core Mapping
核心映射

JavaRust
Threadstd::thread::spawn
ExecutorServiceasync runtime or manual thread orchestration
异步运行时或手工线程编排
synchronized mutable state
同步共享可变状态
Mutex<T>
concurrent shared ownership
并发共享所有权
Arc<T>
queues and handoff
队列与交接
channels

Shared State
共享状态

#![allow(unused)]
fn main() {
use std::sync::{Arc, Mutex};
use std::thread;

let counter = Arc::new(Mutex::new(0));
}

Rust makes the ownership and synchronization cost explicit in the type spelling.
Rust 会把所有权和同步成本直接写在类型上,不让它们偷偷躲起来。

Send and Sync
SendSync

These marker traits are part of what makes Rust concurrency feel stricter:
Rust 并发之所以显得更严,SendSync 是关键原因之一:

  • Send: a value can move across threads
    值可以跨线程移动。
  • Sync: references to a value can be shared across threads safely
    值的引用可以安全地跨线程共享。

Java developers rarely think at this level because the JVM and library conventions hide it.
Java 开发者很少在这个层面思考问题,因为 JVM 和库约定通常把这层细节藏起来了。

Advice
建议

  • prefer message passing when shared mutable state is not necessary
    只要能避免共享可变状态,就优先消息传递。
  • when shared state is necessary, make the synchronization type explicit
    共享状态躲不过去时,就把同步类型老老实实写出来。
  • let the compiler teach where thread-safety assumptions break
    让编译器来指出线程安全假设在哪些地方站不住。

Rust does not make concurrency easy by hiding the problem. It makes it safer by forcing the important parts into the type system.
Rust 不是靠把并发问题藏起来来显得简单,而是靠把关键约束推进类型系统里来变得更安全。