Rust編程進階:044、多線程

例子:

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

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

//     for i in 1..5 {
//         println!("number {} in main thread!", i);
//         thread::sleep(Duration::from_millis(1));
//     }

//     handle.join().unwrap(); // 等待子線程結束
// }

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

    handle.join().unwrap(); // 等待子線程結束

    println!("+++++++++++++++++++++");
    for i in 1..5 {
        println!("number {} in main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

本節全部源代碼:
https://github.com/anonymousGiga/learn_rust/blob/master/learn_thread/src/main.rs

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章