funcsay(s string, delay int, c chanstring){var res stringfor i :=0; i <5; i++{
time.Sleep(time.Duration(delay)* time.Millisecond)
res += s
}
c <- res
}funcmain(){
c :=make(chanstring)gosay("world",1000, c)gosay("hello",500, c)
res_1 :=<-c
fmt.Println("1: ", res_1)
res_2 :=<-c
fmt.Println("2: ", res_2)}
结果:
1: hellohellohellohellohello
2: worldworldworldworldworld
go程、信道go程 轻量级线程下面程序流程main中启动2个拼接字符串的go程,明显可以看出hello拼接耗时更短、world拼接耗时很长随后使用res_1接收信道c中的数据流(此时阻塞),当hello先行拼接成功,数据流成功从c流向res_1后,执行fmt打印res_1func say(s string, delay int, c chan string) { var res string for i := 0; i < 5; i++ { time.Sleep(time.Du.