01-多线程基础

多线程基础 — Rust By Practice

内容来源 · Rust By Practice / Rust 语言实战

原文链接: https://practice-rust.beatai.org/threads/basic-using.html

多线程基础

使用 std::thread::spawn 创建新线程,用 JoinHandle 的 join 等待线程结束。

  1. 🌟
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// 让代码工作
use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..3 {
            println!("hi number {} from the spawned thread", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..3 {
        println!("hi number {} from the main thread", i);
        thread::sleep(Duration::from_millis(1));
    }
    println!("Success!");
}
  1. 🌟
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// 让代码工作:主线程应等待子线程结束
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..3 {
            println!("spawned: {}", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

  __;

    println!("Success!");
}
  1. 🌟🌟
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// 让代码工作
use std::thread;

fn main() {
    let v = vec![1, 2, 3];

    let handle = thread::spawn(move || {
        println!("Here's a vector: {:?}", v);
    });

    handle.join().unwrap();
    println!("Success!");
}
  1. 🌟🌟
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// 填空
use std::thread;

fn main() {
    let s = String::from("hello");

    let handle = thread::spawn(move || {
        println!("{}", s);
    });

    // 取消下面这行的注释并修复错误
    // println!("{}", s);

    handle.join().unwrap();
    println!("Success!");
}

你可以在这里找到答案(在 solutions 路径下),但请只在需要时使用

最后修改 August 23, 2026: 更新 (499855b16)