代码如下:
```
package main
import "fmt"
func main() {
ch1 := make(chan int, 1)
go func() {
for i := 0; i < 10; i++ {
fmt.Printf("Sender: sending element %v ... \n", i)
ch1 <- i
}
fmt.Println("Sender: close the channel")
close(ch1)
}()
for {
elem, ok := <-ch1
if !ok {
fmt.Println("Receiver: closed the channel")
break
}
fmt.Printf("Receiver: received an element%v \n", elem)
}
fmt.Println("End!")
}
```
输出结果:
```
Sender: sending element 0 ...
Sender: sending element 1 ...
Sender: sending element 2 ...
Receiver: received an element0
Receiver: received an element1
Receiver: received an element2
Sender: sending element 3 ...
Sender: sending element 4 ...
Sender: sending element 5 ...
Receiver: received an element3
Receiver: received an element4
Receiver: received an element5
Sender: sending element 6 ...
Sender: sending element 7 ...
Sender: sending element 8 ...
Receiver: received an element6
Receiver: received an element7
Receiver: received an element8
Sender: sending element 9 ...
Sender: close the channel
Receiver: received an element9
Receiver: closed the channel
End!
```
我的问题是为什么一次能发3个元素,但通道的缓冲区只设置为了1啊,是因为go func(){}()开启了3个goroutine吗?
麻烦解答一下,谢谢
有疑问加站长微信联系(非本文作者)