方法一:使用无缓冲协程的阻塞机制
代码语言:javascript
复制package main
import (
"fmt"
"sync"
)
var POOL = 100
func groutine1(p chan int, group *sync.WaitGroup) {
defer group.Done()
for i := 1; i <= POOL; i {
p <- i
if i%2 == 1 {
fmt.Println("groutine-1:", i)
}
}
}
func groutine2(p chan int, group *sync.WaitGroup) {
defer group.Done()
for i := 1; i <= POOL; i {
<-p
if i%2 == 0 {
fmt.Println("groutine-2:", i)
}
}
}
func main() {
msg := make(chan int)
var s sync.WaitGroup
s.Add(2)
go groutine1(msg, &s)
go groutine2(msg, &s)
s.Wait()
}
方法二 使用全局变量
代码语言:javascript
复制package test
import (
"fmt"
"testing"
)
func TestChannel(t *testing.T) {
nowValue := -1
nMax := 100
nChan := make(chan int, 2)
//输出奇数
go func() {
for i := 0; i <= nMax && i%2 == 0; {
if i-1 == nowValue {
nChan <- i
i = 2
}
}
}()
//输出偶数
go func() {
for i := 1; i <= nMax && i%2 != 0; {
if i-1 == nowValue {
nChan <- i
i = 2
}
}
}()
for nowValue < nMax {
nowValue = <-nChan
fmt.Println(nowValue)
}
}