code
package main
import (
"fmt"
"time"
)
func chanTest(ch chan int) {
for { //select外层需要循环 select { case value,ok := <-ch: fmt.Println(value,ok,time.Now()) if ok == false { fmt.Println("chan已经关闭",time.Now()) //select要自己判断退出,如果是for..range 形式,在读取完了关闭的chanel后,退出循环 return } default: fmt.Println("chan 空了",time.Now()) time.Sleep(time.Second * 5) //分支的处理会阻塞整个select } } } func main() { var ch = make(chan int,100) go chanTest(ch) ch <- 1 ch <- 2 time.Sleep(time.Second * 2) ch <- 3 ch <- 4 time.Sleep(time.Second) close(ch) for { time.Sleep(time.Second) } }
需要注意的是,select的 defalut会丢弃数据,chan已满的情况,入chan的数据会被丢弃
引用
原文链接:https://www.f2er.com/go/187127.html