交替打印 依次打印

https://mp.weixin.qq.com/s/I5va3PI1oGIj8R_n3Nw2yw

 

1115. 交替打印 FooBar - 力扣(LeetCode) https://leetcode.cn/problems/print-foobar-alternately/description/

func main() {
    odd := make(chan struct{}, 1)
    even := make(chan struct{}, 1)

    odd <- struct{}{}

    wg := sync.WaitGroup{}

    wg.Add(2)
    a := func() {
        for i := 1; i <= 9; i += 2 {
            <-odd
            print(i, "\n")
            even <- struct{}{}
        }
        wg.Done()
    }

    b := func() {
        for i := 2; i <= 9; i += 2 {
            <-even
            print(i, "\n")
            odd <- struct{}{}
        }
        wg.Done()
    }

    go a()
    go b()
    wg.Wait()
}

 

 

posted @ 2020-02-10 12:06  papering  阅读(145)  评论(0编辑  收藏  举报