channel练习
- 长度为10的带缓冲channel
- 每秒生产一条数据
- 每秒消费一条数据
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 10)
index := 1
productTimer := time.NewTicker(1 * time.Second)
defer productTimer.Stop()
go func(t *time.Ticker) {
for {
<-t.C
ch <- index
fmt.Printf("product: %d\n", index)
index++
if index > 20 {
fmt.Println("close producter.")
close(ch)
return
}
}
}(productTimer)
consumerTimer := time.NewTicker(1 * time.Second)
defer consumerTimer.Stop()
for {
<-consumerTimer.C
i, notClosed := <-ch
if !notClosed {
break
}
fmt.Printf("recive: %d\n", i)
}
fmt.Println("main return.")
}