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

栏目: Go · 发布时间: 5年前

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

在线运行


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTML5移动Web开发指南

HTML5移动Web开发指南

唐俊开 / 电子工业出版社 / 2012-3-1 / 59.00元

HTML5移动Web开发指南,ISBN:9787121160837,作者:唐俊开 著一起来看看 《HTML5移动Web开发指南》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具