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 }