select的使用类似于switch语句,有case和default分支。其中每个case对应一个通道的通信过程:
1、select可以同时监听一个或多个channel,直到其中一个channel ready;
2、如果多个channel同时ready,则随机选择一个执行;
3、可以用于判断管道是否存满;
package main import ( "fmt" "time" ) func test01(ch chan string) { time.Sleep(2*time.Second) ch<-"test01" } func test02(ch chan string) { time.Sleep(2*time.Second) ch<-"test02" } func main() { //定义两个管道 opt01:=make(chan string) opt02:=make(chan string) go test01(opt01) go test02(opt02) select { case s1 := <-opt01: fmt.Println("s1:::", s1) case s2 := <-opt02: fmt.Println("s2:::", s2) } }
浙公网安备 33010602011771号