```rust use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time::Duration; #[derive(Clone, Debug)] enum Next { Child, Main, } fn main() { let next = Arc::new(Mutex::new(Next::Main)); let cond = Arc::new(Condvar::new()); let next2 = next.clone(); let cond2 = cond.clone(); let handle = thread::spawn(move || { let lock = next2.lock().unwrap(); let mut next_flag = (*lock).clone(); drop(lock); for i in 1..=3 { while let Next::Main = next_flag { next_flag = (*cond2.wait(next2.lock().unwrap()).unwrap()).clone(); } // next_flag 为 Next::Child 时跳出 while-loop eprintln!("child:\t{}", i); next_flag= Next::Main; *next2.lock().unwrap() = next_flag.clone();// 下一个进行打印的是main线程 } }); for i in 1..=3 { eprintln!("main:\t{}", i); let mut next_flag = next.lock().unwrap(); *next_flag = Next::Child; // 下一个进行打印的是child线程 drop(next_flag); cond.notify_one(); thread::sleep(Duration::from_secs(1)); //睡一秒, 给child线程提供上锁的机会. } handle.join().unwrap(); } ```