我用打印数字来做案例吧
一个打印奇数
一个打印偶数
上代码
package main
import (
"fmt"
)
// 偶数打印
func PrintEven(ch chan int) {
for {
data := <-ch
fmt.Println("goroutine2:", data+1)
}
}
// 主线打印奇数
func main() {
ch := make(chan int)
go PrintEven(ch)
for i := 1; i <= 10; i += 2 {
fmt.Println("goroutine1:", i)
ch <- i
}
}
输出
goroutine1: 1
goroutine1: 3
goroutine2: 2
goroutine2: 4
goroutine1: 5
goroutine1: 7
goroutine2: 6
goroutine2: 8
goroutine1: 9