使用goroutine,模拟4个售票口出售火车票的案例。4个售票口同时卖票
package main import ( "fmt" "math/rand" "sync" "time" ) var ticket =10 var mutex sync.Mutex //创建锁头 var wg sync.WaitGroup //同步等待组对象 func main(){ /* 4个售票口 */ wg.Add(4) go saleTickets("售票窗口1") go saleTickets("售票窗口2") go saleTickets("售票窗口3") go saleTickets("售票窗口4") wg.Wait() fmt.Println("售票结束") } func saleTickets(name string){ rand.Seed(time.Now().UnixNano()) defer wg.Done() for { //上锁 mutex.Lock() if ticket >0 { time.Sleep(time.Duration(rand.Intn(1000))*time.Microsecond) fmt.Println(name,"售出:",ticket) ticket-- }else{ mutex.Unlock()//条件不满足解锁 fmt.Println(name,"售罄,没有票了……") break } mutex.Unlock() } }