例子:
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