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

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. var POOL = 100
  7. func groutine1(p chan int) {
  8. for i := 1; i <= POOL; i++ {
  9. p <- i
  10. if i%2 == 1 {
  11. fmt.Println("groutine-1:", i)
  12. }
  13. }
  14. }
  15. func groutine2(p chan int) {
  16. for i := 1; i <= POOL; i++ {
  17. <-p
  18. if i%2 == 0 {
  19. fmt.Println("groutine-2:", i)
  20. }
  21. }
  22. }
  23. func main() {
  24. msg := make(chan int)
  25. go groutine1(msg)
  26. go groutine2(msg)
  27. time.Sleep(time.Second * 1)
  28. }

运行结果

  1. groutine-1: 1
  2. groutine-2: 2
  3. groutine-1: 3
  4. groutine-2: 4
  5. groutine-1: 5
  6. groutine-2: 6
  7. groutine-1: 7
  8. groutine-2: 8
  9. groutine-1: 9
  10. groutine-2: 10
  11. groutine-1: 11
  12. groutine-2: 12
  13. groutine-1: 13
  14. groutine-2: 14
  15. groutine-1: 15
  16. groutine-2: 16
  17. groutine-1: 17
  18. groutine-2: 18
  19. groutine-1: 19
  20. groutine-2: 20
  21. groutine-1: 21
  22. groutine-2: 22
  23. groutine-1: 23
  24. groutine-2: 24
  25. groutine-1: 25
  26. groutine-2: 26
  27. groutine-1: 27
  28. groutine-2: 28
  29. groutine-1: 29
  30. groutine-2: 30
  31. groutine-1: 31
  32. groutine-2: 32
  33. groutine-1: 33
  34. groutine-2: 34
  35. groutine-1: 35
  36. groutine-2: 36
  37. groutine-1: 37
  38. groutine-2: 38
  39. groutine-1: 39
  40. groutine-2: 40
  41. groutine-1: 41
  42. groutine-2: 42
  43. groutine-1: 43
  44. groutine-2: 44
  45. groutine-1: 45
  46. groutine-2: 46
  47. groutine-1: 47
  48. groutine-2: 48
  49. groutine-1: 49
  50. groutine-2: 50
  51. groutine-1: 51
  52. groutine-2: 52
  53. groutine-1: 53
  54. groutine-2: 54
  55. groutine-1: 55
  56. groutine-2: 56
  57. groutine-1: 57
  58. groutine-2: 58
  59. groutine-1: 59
  60. groutine-2: 60
  61. groutine-1: 61
  62. groutine-2: 62
  63. groutine-1: 63
  64. groutine-2: 64
  65. groutine-1: 65
  66. groutine-2: 66
  67. groutine-1: 67
  68. groutine-2: 68
  69. groutine-1: 69
  70. groutine-2: 70
  71. groutine-1: 71
  72. groutine-2: 72
  73. groutine-1: 73
  74. groutine-2: 74
  75. groutine-1: 75
  76. groutine-2: 76
  77. groutine-1: 77
  78. groutine-2: 78
  79. groutine-1: 79
  80. groutine-2: 80
  81. groutine-1: 81
  82. groutine-2: 82
  83. groutine-1: 83
  84. groutine-2: 84
  85. groutine-1: 85
  86. groutine-2: 86
  87. groutine-1: 87
  88. groutine-2: 88
  89. groutine-1: 89
  90. groutine-2: 90
  91. groutine-1: 91
  92. groutine-2: 92
  93. groutine-1: 93
  94. groutine-2: 94
  95. groutine-1: 95
  96. groutine-2: 96
  97. groutine-1: 97
  98. groutine-2: 98
  99. groutine-1: 99
  100. groutine-2: 100