How to create threads in Rust

Spawn a new thread in Rust using std::thread::spawn and wait for it to finish with join.

Use the std::thread module to spawn a new thread that runs concurrently with the main thread.

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

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

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
    }

    handle.join().unwrap();
}