初学golang通道尝试了如下代码:
```
package main
import (
"fmt"
"time"
)
type Sender chan<- int
type Receiver <-chan int
func main() {
var myChannel = make(chan int, (0))
var number = 6
go func() {
var sender Sender = myChannel
sender <- number // 1
sender <- number // 2
fmt.Println("Sent!") //5
}()
go func() {
var receiver Receiver = myChannel
fmt.Println("Received!", <-receiver) //3
}()
go func() {
var receiver Receiver = myChannel
fmt.Println("Received!", <-receiver) //4
}()
time.Sleep(time.Second)
}
```
定义了一个非缓存myChannel后,在1处应该阻塞了,然后执行了3处,这时候通道里没数据应该执行2处之后阻塞了再执行4处,最后回到5处。
但实际结果是:
Received! 6
Sent!
Received! 6
这是为什么啊?有大神给解释一下吗
有疑问加站长微信联系(非本文作者)