usestd::thread;usestd::time::Duration;fnmain(){// 闭包方法创建线程
thread::spawn(||{foriin1..10{println!("hi number {} from the spawned thread!",i);thread::sleep(Duration::from_millis(1));}});foriin1..5{println!("hi number {} from the main thread!",i);thread::sleep(Duration::from_millis(1));}}
等待线程终止
使用 join 方法等待线程终止
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
usestd::thread;usestd::time::Duration;fnmain(){lethandle=thread::spawn(||{foriin1..10{println!("hi number {} from the spawned thread!",i);thread::sleep(Duration::from_millis(1));}});// 等待线程结束后执行main方法
handle.join().unwrap();foriin1..5{println!("hi number {} from the main thread!",i);thread::sleep(Duration::from_millis(1));}}
传递参数
使用move 关键字,强制将依赖的参数的所有权交给线程内部
1
2
3
4
5
6
7
8
9
10
11
usestd::thread;fnmain(){letv=vec![1,2,3];lethandle=thread::spawn(move||{println!("Here's a vector: {:?}",v);});handle.join().unwrap();}