Go语言教程之边写边学:Goroutines和Channels练习:启动多个Goroutine,每个goroutine都向一个频道添加值
该程序从10个Goroutines开始。我们创建了一个ch字符串通道,并通过同时运行10个goroutines将数据写入该通道。箭头相对于通道的方向指定是发送还是接收数据。指向ch的箭头指定我们要写入通道ch。箭头从ch向外指向指定我们正在从通道ch读取。
示例代码:main.go
package main
import (
"fmt"
"strconv"
)
func main() {
ch := make(chan string)
for i := 0; i < 10; i++ {
go func(i int) {
for j := 0; j < 10; j++ {
ch <- "Goroutine : " + strconv.Itoa(i)
}
}(i)
}
for k := 1; k <= 100; k++ {
fmt.Println(k, <-ch)
}
}
输出:
1 Goroutine : 9
2 Goroutine : 9
3 Goroutine : 2
4 Goroutine : 0
5 Goroutine : 1
6 Goroutine : 5
7 Goroutine : 3
8 Goroutine : 4
9 Goroutine : 7
10 Goroutine : 6
....................
系列文章