Golang使用2个goroutine分别打印奇偶数,顺序输出1-10

package main

import (
    "fmt"
    "sync"
)

func printOdd(ch chan byte, wg *sync.WaitGroup) {
    defer wg.Done()
    for i := 1; i <= 9; i += 2 {
        fmt.Println(i)
        ch <- 1
        <-ch
    }
}

func printEven(ch chan byte, wg *sync.WaitGroup) {
    defer wg.Done()
    for i := 2; i <= 10; i += 2 {
        <-ch
        fmt.Println(i)
        ch <- 1
    }
}

func main() {
    ch := make(chan byte)
    var wg sync.WaitGroup
    wg.Add(2)
    go printOdd(ch, &wg)
    go printEven(ch, &wg)
    wg.Wait()
}

你可能感兴趣的:(Golang使用2个goroutine分别打印奇偶数,顺序输出1-10)