看介绍说,go的select与switch类似。但其实有很大不同
switch执行是顺序的,而select是随机选择:
package main
import (
"fmt"
)
func main() {
c1:=make(chan int,1024)
c2:=make(chan int,1024)
for i:=0;i<1000;i++{
c1<-1
c2<-1
fmt.Println("i===",i)
select{
case <-c1:
fmt.Println("from c1")
case <-c2:
fmt.Println("from c2")
}
}
}
结果:
i=== 0 from c1 i=== 1 from c2 i=== 2 from c1 i=== 3 from c1 i=== 4 from c2 i=== 5 from c2 i=== 6 from c2 i=== 7 from c1 i=== 8 from c1 i=== 9
有疑问加站长微信联系(非本文作者)