@TOC
代码如下
package main
import (
"fmt"
"time"
)
var POOL = 100
func groutine1(p chan int) {
for i := 1; i <= POOL; i++ {
p <- i
if i%2 == 1 {
fmt.Println("groutine-1:", i)
}
}
}
func groutine2(p chan int) {
for i := 1; i <= POOL; i++ {
<-p
if i%2 == 0 {
fmt.Println("groutine-2:", i)
}
}
}
func main() {
msg := make(chan int)
go groutine1(msg)
go groutine2(msg)
time.Sleep(time.Second * 1)
}
测试结果
groutine-1: 1
groutine-2: 2
groutine-1: 3
groutine-2: 4
groutine-1: 5
groutine-2: 6
groutine-1: 7
groutine-2: 8
groutine-1: 9
groutine-2: 10
groutine-1: 11
groutine-2: 12
groutine-1: 13
groutine-2: 14
groutine-1: 15
groutine-2: 16
groutine-1: 17
groutine-2: 18
groutine-1: 19
groutine-2: 20
groutine-1: 21
groutine-2: 22
groutine-1: 23
groutine-2: 24
groutine-1: 25
groutine-2: 26
groutine-1: 27
groutine-2: 28
groutine-1: 29
groutine-2: 30
groutine-1: 31
groutine-2: 32
groutine-1: 33
groutine-2: 34
groutine-1: 35
groutine-2: 36
groutine-1: 37
groutine-2: 38
groutine-1: 39
groutine-2: 40
groutine-1: 41
groutine-2: 42
groutine-1: 43
groutine-2: 44
groutine-1: 45
groutine-2: 46
groutine-1: 47
groutine-2: 48
groutine-1: 49
groutine-2: 50
groutine-1: 51
groutine-2: 52
groutine-1: 53
groutine-2: 54
groutine-1: 55
groutine-2: 56
groutine-1: 57
groutine-2: 58
groutine-1: 59
groutine-2: 60
groutine-1: 61
groutine-2: 62
groutine-1: 63
groutine-2: 64
groutine-1: 65
groutine-2: 66
groutine-1: 67
groutine-2: 68
groutine-1: 69
groutine-2: 70
groutine-1: 71
groutine-2: 72
groutine-1: 73
groutine-2: 74
groutine-1: 75
groutine-2: 76
groutine-1: 77
groutine-2: 78
groutine-1: 79
groutine-2: 80
groutine-1: 81
groutine-2: 82
groutine-1: 83
groutine-2: 84
groutine-1: 85
groutine-2: 86
groutine-1: 87
groutine-2: 88
groutine-1: 89
groutine-2: 90
groutine-1: 91
groutine-2: 92
groutine-1: 93
groutine-2: 94
groutine-1: 95
groutine-2: 96
groutine-1: 97
groutine-2: 98
groutine-1: 99
groutine-2: 100
在线play地址
有疑问加站长微信联系(非本文作者)