线程基础 #

一、创建线程 #

rust
use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("子线程: {}", i);
            thread::sleep(Duration::from_millis(1));
        }
    });
    
    for i in 1..5 {
        println!("主线程: {}", i);
        thread::sleep(Duration::from_millis(1));
    }
}

二、等待线程 #

rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("子线程运行中");
    });
    
    handle.join().unwrap();
    println!("主线程结束");
}

三、move 闭包 #

rust
use std::thread;

fn main() {
    let v = vec![1, 2, 3];
    
    let handle = thread::spawn(move || {
        println!("{:?}", v);
    });
    
    handle.join().unwrap();
}

四、总结 #

本章学习了:

  • 创建线程
  • 等待线程
  • move 闭包
最后更新:2026-03-27