You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.0 KiB

package goConcurrency
import (
"math/rand"
"time"
)
func TimerA() {
// 新建Timer
t := time.NewTimer(time.Second) // *time.Timer
println("Set the timer, \ttime is ", time.Now().String())
// 阻塞从t.C接收数据
now := <-t.C
println("The time is up, time is ", now.String())
}
func TimerC() {
ch := time.After(time.Second)
println("Set the timer, \ttime is ", time.Now().String())
now := <-ch
println("The time is up, time is ", now.String())
}
func TimerB() {
// 初始化
ch := make(chan int)
// goroutine 模拟猜
go func() {
// 随机写入int
for {
// 随机猜
ch <- rand.Intn(10)
// 间隔.4秒
time.Sleep(400 * time.Millisecond)
}
}()
// 模拟每轮游戏结果, for循环结构
// 定时器控制每局时间
t := time.NewTimer(time.Second * 3)
// 初始化统计变量
counter, hint, miss, result := 5, 0, 0, 4
// 开始游戏
for i := 0; i < counter; i++ {
// for + select 结构检测答案
loopGuess:
for {
select {
case v := <-ch: // 接收用户猜的数
println("Guess num is ", v)
//判定是否命中结果
if result == v {
println("Bingo! Hint the number.")
hint++
// 重置定时器
t.Reset(time.Second * 3)
// 进行下一轮
break loopGuess
}
// 判定是否到期
case <-t.C:
println("The time is up, don't hint.")
miss++
// 重新创建定时器
t = time.NewTimer(time.Second * 3)
// 下一轮
break loopGuess
}
}
}
//
println("Game Completed!", "Hint ", hint, " Miss ", miss)
}
func TickerA() {
// 初始化
ticker := time.NewTicker(time.Second)
timer := time.After(5 * time.Second)
// 周期性执行
loopFor:
for t := range ticker.C {
// heart beat
println("HeartBeat, http.Get(https://domain/ping), time ", t.String())
// 控制结束
select {
case <-timer:
// 结束
println("HeartBeat Completed.")
// 关闭ticker
ticker.Stop()
// break for
break loopFor
default:
// 非阻塞的接收
}
}
}