fnmain() { thread::spawn(|| { foriin1..10 { println!("hi number {i} from the spawned thread!"); thread::sleep(Duration::from_millis(1)); } });
foriin1..5 { println!("hi number {i} from the main thread!"); thread::sleep(Duration::from_millis(1)); }
println!("main thread end"); }
这里有几点值得注意:
线程内部的代码使用闭包来执行
main 线程一旦结束,程序就立刻结束
thread::sleep 会让当前线程休眠指定的时间,随后其它线程会被调度运行
来看看输出:
1 2 3 4 5 6 7 8 9 10
hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the spawned thread! hi number 2 from the main thread! hi number 3 from the spawned thread! hi number 3 from the main thread! hi number 4 from the spawned thread! hi number 4 from the main thread! hi number 5 from the spawned thread! main thread end
fnmain() { lethandle = thread::spawn(|| { foriin1..10 { println!("hi number {i} from the spawned thread!"); thread::sleep(Duration::from_millis(1)); } });
**handle.join().unwrap();**
foriin1..5 { println!("hi number {i} from the main thread!"); thread::sleep(Duration::from_millis(1)); }
println!("main thread end"); }
输出为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
hi number 1 from the spawned thread! hi number 2 from the spawned thread! hi number 3 from the spawned thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! hi number 6 from the spawned thread! hi number 7 from the spawned thread! hi number 8 from the spawned thread! hi number 9 from the spawned thread! hi number 1 from the main thread! hi number 2 from the main thread! hi number 3 from the main thread! hi number 4 from the main thread! main thread end