点击运行
package main import ( "fmt" "time" ) func write(ch chan int) { for i := 0; i < 5; i++ { ch <- i fmt.Println("成功写入 ", i, "到通道中") } close(ch) } func main() { ch := make(chan int, 2) go write(ch) time.Sleep(2 * time.Second) for v := range ch { fmt.Println("从通道中读取值 ", v) time.Sleep(2 * time.Second) } }
运行结果 :
正在执行...