package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var wg sync.WaitGroup
var mutex sync.Mutex
var tickets = 100
func main() {
rand.Seed(time.Now().UnixNano())
wg.Add(4)
var chan1 = make(chan int, 1)
var chan2 = make(chan int, 1)
var chan3 = make(chan int, 1)
var chan4 = make(chan int, 1)
go mai("1号窗口", chan1)
go mai("2号窗口", chan2)
go mai("3号窗口", chan3)
go mai("4号窗口", chan4)
for i := 0; i <= 103; i++ {
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
switch i % 4 {
case 0:
fmt.Println(i+1, "号顾客正在1号窗口买票")
chan1 <- i
case 1:
fmt.Println(i+1, "号顾客正在2号窗口买票")
chan2 <- i
case 2:
fmt.Println(i+1, "号顾客正在3号窗口买票")
chan3 <- i
case 3:
fmt.Println(i+1, "号顾客正在4号窗口买票")
chan4 <- i
}
}
wg.Wait()
fmt.Println("结束")
}
func mai(num string, ch chan int) {
rand.Seed(time.Now().UnixNano())
defer wg.Done()
for {
i := <-ch
mutex.Lock()
if tickets > 0 {
fmt.Println(i+1, "号客人在", num, "买到票", tickets)
tickets--
} else {
fmt.Println(i+1, "号客人", "来晚了,票卖完了")
mutex.Unlock()
break
}
mutex.Unlock()
}
}
最后修改:2022 年 03 月 19 日
© 允许规范转载
2 条评论
你的文章内容非常卖力,让人点赞。 http://www.55baobei.com/qj0FUkDRqH.html
《我为女儿打造末世堡垒》短片剧高清在线免费观看:https://www.jgz518.com/xingkong/15918.html