majianyu
3/15/2019 - 8:49 PM

使用2个协程交替打印奇偶数

package main

import (
	"fmt"
	"time"
)

func main() {
	msg := make(chan int)
	go foo(msg)
	go bar(msg)
	time.Sleep(1 * time.Second)

}

var pool = 100

func foo(p chan int) {
	for i := 1; i <= pool; i++{
		p <- i
		if i%2 == 1 {
			fmt.Printf("奇数\t%d\n", i)
		}
	}
}
func bar(p chan int) {
	for i:= range p {
		if i%2 == 0 {
			fmt.Printf("偶数\t%d\n", i)
		}

	}
}