import (
"fmt"
"time"
)
// 设置定时器 每隔一秒钟一次
var tk = time.NewTicker(time.Second)
var chanInt = make(chan int)
func main() {
num := 1
go func() {
// tk.C 定时返回一个管道
for range tk.C {
select {
case chanInt <- 1:
fmt.Println("存入1")
case chanInt <- 2:
fmt.Println("存入2")
case chanInt <- 3:
fmt.Println("存入3")
}
}
}()
for v := range chanInt {
fmt.Printf("收到了 %v\n", v)
num++
if num > 10 {
tk.Stop()
break
}
}
}
输出
存入3
收到了 3
存入3
收到了 3
存入1
收到了 1
存入2
收到了 2
存入3
收到了 3
存入3
收到了 3
存入3
收到了 3
存入3
收到了 3
存入3
收到了 3
存入2
收到了 2