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

雷域 · · 1886 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

@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地址

在线运行


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:雷域

查看原文:golang两个协成交替打印1-100的奇数偶数

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1886 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传