15_Timer的使用.go
package main
import (
"fmt"
"time"
)
//验证time.NewTimer(),时间到了,只会响应一次
func main() {
timer := time.NewTimer(1 * time.Second)
for {
<-timer.C
fmt.Println("时间到")
}
}
func main01() {
//创建一个定时器,设置时间为2s,2s后,往time通道写内容(当前时间)
timer := time.NewTimer(2 * time.Second)
fmt.Println("当前时间:", time.Now())
//2s后,往timer.C写数据,有数据后,就可以读取
t := <-timer.C //channel没有数据前后阻塞
fmt.Println("t = ", t)
}
16_通过Timer实现延时功能.go
package main
import (
"fmt"
"time"
)
func main() {
<-time.After(2 * time.Second) //定时2s,阻塞2s, 2s后产生一个事件,往channel写内容
fmt.Println("时间到")
}
func main02() {
time.Sleep(2 * time.Second)
fmt.Println("时间到")
}
func main01() {
//延时2s后打印一句话
timer := time.NewTimer(2 * time.Second)
<-timer.C
fmt.Println("时间到")
}
17_停止和重置定时器.go
package main
import (
"fmt"
"time"
)
func main() {
timer := time.NewTimer(3 * time.Second)
ok := timer.Reset(1 * time.Second) //重新设置为1s
fmt.Println("ok = ", ok)
<-timer.C
fmt.Println("时间到")
}
func main01() {
timer := time.NewTimer(3 * time.Second)
go func() {
<-timer.C
fmt.Println("子协程可以打印了,因为定时器的时间到")
}()
timer.Stop() //停止定时器
for {
}
}
18_Ticker的使用.go
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(1 * time.Second)
i := 0
for {
<-ticker.C
i++
fmt.Println("i = ", i)
if i == 5 {
ticker.Stop()
break
}
}
}
19_fibonacci数列.go
//fibonacci 1 1 2 3 5 8
package main
import (
"fmt"
)
//ch只写,quit只读
func fibonacci(ch chan<- int, quit <-chan bool) {
x, y := 1, 1
for {
//监听channel数据的流动
select {
case ch <- x:
x, y = y, x+y
case flag := <-quit:
fmt.Println("flag = ", flag)
return
}
}
}
func main() {
ch := make(chan int) //数字通信
quit := make(chan bool) //程序是否结束
//消费者,从channel读取内容
//新建协程
go func() {
for i := 0; i < 8; i++ {
num := <-ch
fmt.Println(num)
}
//可以停止
quit <- true
}() //别忘了()
//生产者,产生数字,写入channel
fibonacci(ch, quit)
}
20_通过select实现超时.go
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
quit := make(chan bool)
//新开一个协程
go func() {
for {
select {
case num := <-ch:
fmt.Println("num = ", num)
case <-time.After(3 * time.Second):
fmt.Println("超时")
quit <- true
}
}
}() //别忘了()
for i := 0; i < 5; i++ {
ch <- i
time.Sleep(time.Second)
}
<-quit
fmt.Println("程序结束")
}