go 的chan01
点击查看代码
package main
import (
"fmt"
"time"
)
func write(ch chan int) {
for i := 0; i < 5; i++ {
ch <- i
fmt.Println("successfully wrote", i, "to ch")
}
fmt.Println("关闭ch")
close(ch)
}
func test2(){
ch := make(chan string, 3)
var s string
ch <- "hello"
ch <- "world"
ch <- "!"
//ch <- "test"
s = <-ch
s1 := <-ch
s2 := <-ch
fmt.Println(s, s1, s2)
}
func main() {
ch := make(chan int, 2)
//ch := make(chan int)
go write(ch)
//write(ch)
time.Sleep(50 * time.Second)
for v := range ch { // range会重复从ch中获取数据,直到他自动关闭
fmt.Println("read value", v, "from ch")
time.Sleep(1 * time.Second)
}
test2()
}
写入自己的博客中才能记得长久