侧边栏壁纸
博主头像
Lin2J博主等级

升级了服务器,访问应该会更加流畅🇨🇳

  • 累计撰写 94 篇文章
  • 累计创建 39 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录
Go

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

Lin2J
2021-02-20 / 0 评论 / 0 点赞 / 713 阅读 / 774 字 / 正在检测是否收录...
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
0

评论区