利用go语言级并发特点实现经典的卖票案例,案例:启动10个窗口模拟售卖100张车票,打印出票信息。
import (
"fmt"
"time"
)
type ticket struct {
no int //票号
}
var tickets = make(chan ticket,100)
func main() {
for i:=1;i<=100;i++{
tickets<-ticket{no:i}
}
for i:=1;i<=10;i++{
go sale(i)
}
time.Sleep(time.Second*4)
fmt.Println("over")
}
func sale(winNo int){
for len(tickets)>0{
fmt.Printf("窗口%d售卖车票号%v\n",winNo,<-tickets)
time.Sleep(time.Microsecond)
}
}