go的chan
无缓冲区channel
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int) // 创建无缓冲channel
go func() {
fmt.Println("time sleep 5 second...")
time.Sleep(5 * time.Second)
<-ch
}()
fmt.Println("即将阻塞...")
ch <- 1 // 协程将会阻塞,等待数据被读取
fmt.Println("ch 数据被消费,主协程退出")
}
结果,消费完才能继续
即将阻塞...
time sleep 5 second...
ch 数据被消费,主协程退出