• GoLang 使用协程和管道获取随机数


     1 package main
     2 
     3 import (
     4     "fmt"
     5     "math/rand"
     6     "time"
     7 )
     8 
     9 var (
    10     //Count 统计获取随机数的个数
    11     Count int = 0
    12     //MaxRandomNumberLength 最大随机数长度
    13     MaxRandomNumberLength int = 100
    14     //RandomNumberRange 随机数范围
    15     RandomNumberRange int = 1000
    16 )
    17 
    18 //CreateRandomeNumber 创建随机数 协程
    19 func CreateRandomeNumber(RandomChan chan int, ExitChan chan bool) {
    20     rand.Seed(time.Now().UnixNano())
    21     for i := 0; i < MaxRandomNumberLength; i++ {
    22         RandomChan <- rand.Intn(RandomNumberRange) + 1
    23         Count++
    24     }
    25     fmt.Printf("一共获取 %v 个随机数
    ", Count)
    26     close(RandomChan)
    27     ExitChan <- true
    28 }
    29 
    30 //SortRandomNumber 随机数排序 协程
    31 func SortRandomNumber(Randomchan chan int, SortChan chan int, ExitChan chan bool) {
    32     var Arr []int
    33     Arr = make([]int, MaxRandomNumberLength)
    34 
    35     for i := 0; i < len(Arr); i++ {
    36         Arr[i] = <-Randomchan
    37     }
    38 
    39     for i := 0; i < len(Arr)-1; i++ {
    40         for j := 0; j < len(Arr)-1-i; j++ {
    41             if Arr[j] > Arr[j+1] {
    42                 Arr[j], Arr[j+1] = Arr[j+1], Arr[j]
    43             }
    44         }
    45     }
    46 
    47     for i := 0; i < len(Arr); i++ {
    48         SortChan <- Arr[i]
    49     }
    50     close(SortChan)
    51     ExitChan <- true
    52 }
    53 
    54 //EnterTheSortedRandomNumber 输出排序后的随机数
    55 func EnterTheSortedRandomNumber(SortChan chan int, ExitChan chan bool) {
    56     for value := range SortChan {
    57         fmt.Println(value)
    58     }
    59     ExitChan <- true
    60 }
    61 func main() {
    62     // 创建管道
    63     RandomChan := make(chan int)
    64     SortChan := make(chan int)
    65     ExitChan := make(chan bool, 3)
    66 
    67     //开启协程
    68     go CreateRandomeNumber(RandomChan, ExitChan)
    69     go SortRandomNumber(RandomChan, SortChan, ExitChan)
    70     go EnterTheSortedRandomNumber(SortChan, ExitChan)
    71 
    72     fmt.Println("主线程等待协程中...")
    73     func() {
    74         for i := 0; i < 3; i++ {
    75             <-ExitChan
    76             fmt.Println("协程完成工作...")
    77         }
    78         close(ExitChan)
    79     }()
    80     fmt.Println("主线程结束")
    81 }
    时间若流水,恍惚间逝去
  • 相关阅读:
    centos7 安装高版本svn
    idea 常用快捷键
    IDEA 打可执行jar包(maven项目)
    服务器安装JDK
    阿里云服务器连接AWS-S3
    mysql5.7 修改密码,修改权限
    win10 手动安装mysql-8.0.11-winx64.zip
    centos7 关闭防火墙
    centos7 配置阿里云yum源
    centos7 源码安装nginx
  • 原文地址:https://www.cnblogs.com/alanshreck/p/14141735.html
Copyright © 2020-2023  润新知