golang 两个协程交替打印1-100的奇数偶数

Lin2J
2021-02-20 / 0 评论 / 507 阅读
温馨提示:
本文最后更新于2021-02-20,若内容或图片失效,请留言反馈。
package main

import (
	"fmt"
	"time"
)

var Pool = 100

// 打印奇数
func printOdd(msg chan int) {
	for i := 1; i < Pool; i++ {
		msg <- i
		if (i & 1) == 1 {
			fmt.Println("goroutine-1:", i)
		}
	}
}

func printEven(msg chan int) {
	for i := 1; i < Pool; i++ {
		<-msg
		if (i & 1) == 0 {
			fmt.Println("goroutine-2:", i)
		}
	}
}

func main() {
	msg := make(chan int)
	go printOdd(msg)
	go printEven(msg)

	time.Sleep(3 * time.Second)
}

输出

goroutine-1: 1
goroutine-2: 2
goroutine-1: 3
goroutine-2: 4
goroutine-1: 5
goroutine-2: 6
goroutine-1: 7
goroutine-2: 8
goroutine-1: 9
goroutine-2: 10
goroutine-1: 11
...
goroutine-2: 92
goroutine-1: 93
goroutine-2: 94
goroutine-1: 95
goroutine-2: 96
goroutine-1: 97
goroutine-2: 98
goroutine-1: 99
goroutine-2: 100