Create a new thread in Rust using std::thread::spawn and wait for it to complete with join.
Use std::thread::spawn to create a new thread that runs a closure, then call .join() on the returned handle to wait for it to finish.
use std::thread;
use std::time::Duration;
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("number {i}!");
thread::sleep(Duration::from_millis(1));
}
});
handle.join().unwrap();
}
Creating threads in Rust with std::thread establishes a separate line of execution that runs code simultaneously with your main program. This matters because it lets your application do multiple things at once, like downloading a file while keeping the user interface responsive. Think of it as hiring a second worker to handle a task while you continue with your own.